How to use `$lookups` to iterate object id inside array

Viewed 66

i am have 2 collection. 1) product 2) product category. i have to populate category name based on its category id.

Product Category:

[
{
   "_id": "123",
   "name": "sample category 1"
},
{
   "_id": "456",
   "name": "sample category 2"
},
]

Product:

[
{
   "_id": "789",
   "product_name": "test product1",
   "items":[
      {
         "price": 55,
         "image": "default.png",
         "category":[
             "123",
          ],
      }
    ]
}
...
]

I tried $lookups like this but it doesn't works out.

  {
        from: "product_category",
        localField: 'items.category',
        foreignField: '_id',
        as: 'items.category',
        model: 'ProductCategory',
      },

I was expecting result like this.

[
{
   "_id": "789",
   "product_name": "test product1",
   "items":[
      {
         "price": 55,
         "image": "default.png",
         "category":[
            {
              "_id": "123",
              "name": "sample category 1"
            } 
          ]
      }
    ]
}
...
]

can anyone tell me whats wrong in this code.

1 Answers

You have to first $unwind the items array and then $group to reconstruct again.

Product.aggregate([
  { "$unwind": "$items" },
  { "$lookup": {
    "from": "product_category",
    "localField": "items.category",
    "foreignField": "_id",
    "as": "items.category"
  }},
  { "$group": {
    "_id": "$_id",
    "items": { "$push": "$items" }
  }}
])
Related