Multiple populates - mongoosejs


Question

Just a simple query, for example with a double ref in the model.

Schema / Model

var OrderSchema = new Schema({

    user: {
        type    : Schema.Types.ObjectId,
        ref     : 'User',
        required: true
    },

    meal: {
        type    : Schema.Types.ObjectId,
        ref     : 'Meal',
        required: true
    },
});

var OrderModel = db.model('Order', OrderSchema);

Query

OrderModel.find()
    .populate('user') // works
    .populate('meal') // dont works
    .exec(function (err, results) {
         // callback
    });

I already tried something like

.populate('user meal')
.populate(['user', 'meal'])

In fact only one of the populates works.

So, how do is get two populates working ?

1
33
10/10/2012 2:27:45 PM

Accepted Answer

You're already using the correct syntax of:

OrderModel.find()
    .populate('user')
    .populate('meal')
    .exec(function (err, results) {
         // callback
    });

Perhaps the meal ObjectId from the order isn't in the Meals collection?

37
10/10/2012 3:15:37 PM

UPDATE:
This solution remains for the version 3.x of Mongoose
http://mongoosejs.com/docs/3.8.x/docs/populate.html
but is no longer documented for >= 4.x versions of Mongoose and so the answer from @JohnnyHK is the only valid one for now on.

ORIGINAL POST
If you're using Mongoose >= 3.6, you can pass a space delimited string of the path names to populate:

OrderModel.find()
    .populate('user meal')
    .exec(function (err, results) {
         // callback
    });

http://mongoosejs.com/docs/populate.html


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon