The deep virtual population in mongoose is actually very simple!
mongoose’s virtual population is very useful tool. You can mention population path in schema as a virtual field and mongoose will automatically query and push all virtual documents for you while find query (and find like queries) by using populate method on query builder.
But there is a catch.
Let’s say you have a blog collection where resides lots of blogs. Blog schema have a virtually populated field author.
blogSchema = new mongoose.Schema({});
blogSchema.virtual('author', {
ref : 'User', // fetch from User model
localField : 'authorId',
foreignField : 'userId',
justOne : true
})
In user schema, we have a virtual path photos which is used to fetch photos of user.
userSchema = new mongoose.Schema({});
userSchema.virtual('photos', {
ref : 'Photo', // fetch from Photo model
localField : 'userId', // ↓
foreignField : 'uploaderId'
})
Now, when you fetch blogs and populate author like below…
blogModel.find({}).populate('author').exec(callback);
..you kinda also want author document to have photos in it, but author document (user document) is not populated (or asked to populate photos path), it will…