unknowndomain
unknowndomain

Reputation: 985

Mongoose .populate() not populating

I've tried a few different things, and I just can't get Mongoose to populate Users information into the Items collection.

File: users.js

var mongoose = require( 'mongoose' )
    Schema = mongoose.Schema,
    ObjectId = Schema.Types.ObjectId;

var userSchema = Schema( {
    _id: ObjectId,
    barcode: String,
    name: String,
    email: String,
    type: String
} );

var Users = mongoose.model( 'Users', userSchema );

module.exports = Users;
module.exports.schema = userSchema;

File: items.js

var mongoose = require( 'mongoose' )
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId,
    Users = require( __dirname + '/users' ),
    userSchema = Users.schema;

var itemSchema = Schema( {
    _id: ObjectId,
    name: String,
    barcode: String,
    transactions: [ {
        date: Date,
        user: { type: ObjectId, ref: 'Users' },
        status: String
    } ]
} );

var Items = mongoose.model( 'Items', itemSchema );

module.exports = Items;
module.exports.schema = itemSchema;

This is my test code:

var mongoose = require( 'mongoose' );
mongoose.connect( 'mongodb://localhost/booker' );

var Users = require( __dirname + '/models/users' );
var Items = require( __dirname + '/models/items' );

Items.findOne().populate( 'user' ).exec( function( err, arr ) {
    console.log( arr );
} );

Essentially the issue is that the array isn't populating the user information into the items.

What am I doing wrong?

Upvotes: 2

Views: 1814

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312115

The user field that you're populating is nested within a sub-doc of your transactions array field so you need to include its full path in the populate call:

Items.findOne().populate( 'transactions.user' ).exec( function( err, arr ) {
    console.log( arr );
} );

Upvotes: 4

Related Questions