Home > Mobile >  Mongoose populate first and then filter based on populated field
Mongoose populate first and then filter based on populated field

Time:11-03

I have two collections (items, and subitems). The items collection has an object reference to subitems collection in subItems property (It's an array of subItem ObjectIds).

I want to build a query where I can first populate the subItems, and then filter based on populated field. I tried running the query below, but it seems that populate is ran last, therefore subItems[0].sharedGroups.groupId can never be filtered properly because it's not populated yet.

db.items.find({
        $or: [
          { 'owner': 1 },
          { 'subItems[0].sharedGroups.groupId': { $in: [3691] } },
        ]
}).populate('subItems');

CodePudding user response:

you should use $lookup and then $match in aggregation like this

db.items.aggregate([
  {
    $lookup:{
      from:"subItems",
      localField:"subItems", // field of reference to subItem
      foreignField:"_id",
      as :"subItems"
    }},
  {
    $match:
        {
          $or: [
            { 'owner': 1 },
            { 'subItems.sharedGroups.groupId': { $in: [3691] } },
          ]
        }
  }]
  )
  • Related