Mongoose: deep population (populate a populated field) Mongoose: deep population (populate a populated field) mongoose mongoose

Mongoose: deep population (populate a populated field)


Firstly, update mongoose 3 to 4 & then use the simplest way for deep population in mongoose as below :

Suppose you have Blog schema having userId as ref Id & then in User you have some review as ref Id for schema Review. So Basically, you have three schema :1. Blog2. User3. Review

And, you have to query from blog, which user owns this blog & the user review.So you can query your result as :

BlogModel  .find({})  .populate({    path : 'userId',    populate : {      path : 'reviewId'    }  })  .exec(function (err, res) {  })


Populating 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' }]});

Populate lets you get a list of a user's friends, but what if you also wanted a user's friends of friends? Specify the 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' }});

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