1

Im trying to populate the second nested array after using aggregate $lookup.

This is my original array.

 {
    "_id" : ObjectId("607da9c0c7cb26384c7810a6"), 
    "date" : ISODate("2021-04-20T00:00:00.000+0000"), 
    "clientID" : "601e6dc61766587af8ce76db", 
    "medications" : [
        {
            "_id" : ObjectId("6065de3aa95e721f587f7528")
        }, 
    ]
}
{
   from: "medications",
   localField: "medications._id",
   foreignField: "_id",
   as: "medications",
}

after using aggregate $lookup I get this result, but I still have nested array "inventory" that I need to populate. I tried adding another $lookup pipeline, but I don't know how the right way to do that.

{
    "_id" : ObjectId("607da9c0c7cb26384c7810a6"), 
    "date" : ISODate("2021-04-20T00:00:00.000+0000"), 
    "clientID" : "601e6dc61766587af8ce76db", 
    "medications" : {
        "_id" : ObjectId("6065de3aa95e721f587f7528"), 
        "medication": "med 1"
        "schedule": ["9am", "10pm"]
        "inventory":  "ObjectId("6076d55ab6aeb947dca85877")"
    }
}

This is the inventory item

{
   "_id" : ObjectId("6076d55ab6aeb947dca85877"), 
   "item": "Inventory item 1",
   "Qty": "10"
}

Expected Output

{
    "_id" : ObjectId("607da9c0c7cb26384c7810a6"), 
    "date" : ISODate("2021-04-20T00:00:00.000+0000"), 
    "clientID" : "601e6dc61766587af8ce76db", 
    "medications" : {
        "_id" : ObjectId("6065de3aa95e721f587f7528"), 
        "medication": "med 1"
        "schedule": ["9am", "10pm"]
        "inventory":  {
              "_id" : ObjectId("6076d55ab6aeb947dca85877"), 
              "item": "Inventory item 1",
              "Qty": "10"
         }
    }
}

2 Answers 2

1

You can try this one or alternatively use population.

{
   from: "medications",
   localField: "medications._id",
   foreignField: "_id",
   as: "medications",
}
, {
  $unwind: {
    path: "$medications",
    preserveNullAndEmptyArrays: true
  }
}, {
  $lookup: {
    from: "inventory",
    localField: "inventory._id",
    foreignField: "_id",
    as: "medications.inventory",
  }
}

You may check the $unwind in the official documentation. Just pay attention to the appropriate localField and foreignField.

Sign up to request clarification or add additional context in comments.

1 Comment

Is there any other way to expand multiple nested references. Cz its weird to code 4 or 5 lookups just to expand nested references.
0

use populate() to expand nested references.

schemaModel.populate(result, {path: 'result'});

See more at Mongoose docs

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.