Mongoose populate embedded Mongoose populate embedded mongoose mongoose

Mongoose populate embedded


As of Mongoose 3.6 the ability to recursively populate related documents in a query has been added. Here is an example of how you might do it:

 UserList.findById(listId)         .populate('refUserListItems')         .exec(function(err, doc){             UserListItem.populate(doc.refUserListItems, {path:'refSuggestion'},                   function(err, data){                        console.log("User List data: %j", doc);                        cb(null, doc);                   }             );               });           

In this case, I am populating an array of id's in 'refUserListItems' with their referenced documents. The result of the query then gets passed into another populate query that references the field of the original populated document that I want to also populate - 'refSuggestion'.

Note the second (internal) populate - this is where the magic happens. You can continue to nest these populates and tack on more and more documents until you have built your graph the way you need it.

It takes a little time to digest how this is working, but if you work through it, it makes sense.


in Mongoose 4 you can populate multilevel like this (even in different database or instance)

A.find({}).populate({  path: 'b',   model: 'B',  populate: {    path: 'c',    model: 'C'  }}).exec(function(err, a){});


In Mongoose 4 you can populate documents across multiple levels:

Say you have a User schema which keeps track of the user's friends.

var userSchema = new Schema({  name: String,  friends: [{ type: ObjectId, ref: 'User' }]});

Firstly populate() lets you get a list of user friends. But what if you also wanted a user's friends of friends? In that case, you can specify a populate option to tell mongoose to populate the friends array of all the user's friends:

User.  findOne({ name: 'Val' }).  populate({    path: 'friends',    // Get friends of friends - populate the 'friends' array for every friend    populate: { path: 'friends' }  });

Taken from: http://mongoosejs.com/docs/populate.html#deep-populate