Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 552
e382df99a7950919789725ceeec126 Avatar asked Oct 10 '12 14:10

e382df99a7950919789725ceeec126


2 Answers

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?

like image 173
JohnnyHK Avatar answered Sep 24 '22 10:09

JohnnyHK


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

like image 36
Michel Sahli Avatar answered Sep 25 '22 10:09

Michel Sahli