Search code examples
node.jsmongodbmongoosemongoose-populate

Populate mongoose across levels and display certain fields


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

User.
  findOne({ name: 'Val' }).
  populate({
    path: 'friends',
    populate: { path: 'friends' }
  });

The above schema populates the entire User fields for friends array, but for the friends array, I need only name to be populated. How do I limit the fields in the nested level in mongoose.


Solution

  • Generally speaking, you would first populate friends as you have done and then add select to simply get the fields that you wanted to extract from the User model.

    User.findOne({ name: 'Val' })
      .populate({
        path: 'friends',
        select: ['name', 'fieldName']
      })
    

    I have added array of elements to demonstrate that you can select more fields that way, in your case it would just be name.