Search code examples
node.jsmongodbexpressmongoosemongoose-populate

How to populate against foreign keys mongoose?


if (req.params) {
   const val = await userServices.find()
       .where({
           title: req.params.categoryName
       })
       .populate('profileId', null,
           {
               stateId: { $in: [`${req.params.stateId}`] },
               cityId: { $in: [`${req.params.cityId}`] },
           }
       );
   return res.json({
       success: true,
       val
   })
}

Details: Here is the Query for populating profile details, but I want to populate inside foreign keys against StateId and CityId.


Solution

  • Well you can do it this way actually:

    .populate({
        path: 'profileId',
        populate: {path:'stateId'}
      })
    .populate({
        path: 'profileId',
        populate: { path: 'cityId'}
    });
    

    Reference:Deep Populate