Search code examples
javascriptnode.jsmongodbmongoose

Multiple populates - mongoosejs


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 ?


Solution

  • 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?