mongoose Mongoose Population Nested Population


Lets say you have a user schema, which contains name , contactNo, address, and friends.

var UserSchema = new mongoose.Schema({
    name : String,
    contactNo : Number,
    address : String,
    friends :[{
        type: mongoose.Schema.Types.ObjectId,
        ref : User

If you want to find a user, his friends and friends of friends, you need to do population on 2 levels i.e. nested Population.

To find friends and friends of friends:

User.find({_id : userID})
        path : 'friends',
        populate : { path : 'friends'}//to find friends of friends

All the parameters and options of populate can be used inside nested populate too, to get the desired result.

Similarly, you can populate more levels according to your requirement.

It is not recommended to do nested population for more than 3 levels. In case you need to do nested populate for more than 3 levels, you might need to restructure your schema.