How to query specific values from a two level mongoose populate?

const {_id, name, email, role, account, subUsers } = await User.findById(req.user.id)
    .populate({
        path    : 'account',     // need specific values from this accountModel (_id & name)
        populate: [
            { path: 'providers' }, // need specific values from this model (_id & name) 
        ]
    })
    .populate('subUsers', {_id: 1, name: 1});
1 Like

You can pass additional config select and specify what fields you want to be returned:

const {_id, name, email, role, account, subUsers } = await User.findById(req.user.id)
  .populate([ 
    { path: 'account', select: '_id name', populate: [ { path: 'providers', select: '_id name' } ] },
    { path: 'subUsers', select: '_id name' }
  ])
2 Likes

Thank you so much!!!

1 Like