2

I am trying to populate a deeply nested object in an array for quite some time but is of no luck. I tried unwinding the array but the resultant array is being converted into an object instead of an array.

let aggQuery: any = [
            { $match: {} }
    
            {
                $lookup: {
                    from: "tribe-answers", localField: "answers", foreignField: "_id", as: "answers"
                }
            },
             {
                "$unwind": {
                "path": "$answers.createdBy",
                "preserveNullAndEmptyArrays": true
                }
            },
            {
            $lookup: {
                from: "users", localField: "answers.createdBy", foreignField: "_id", as: "answers.createdBy"
            }
            },
            
        ];

Expected output

answers = [
 { _id,
  content
  createdBy{
     _id
     firstname
     lastname
  }
 },
 { _id,
  content
  createdBy{
     _id
     firstname
     lastname
  }
 }
]

Returned Output

answers = {
   _id,
  content
  createdBy{
     _id
     firstname
     lastname
  }
 }

The above query does populate the createdBy field but turns the array into an object. What I need is to populate the createdBy field in every element of an array of answers. Thanks for the help.

1 Answer 1

2
db.getCollection('tribe-posts').aggregate([
    { 
        "$lookup": {
           "from": "tribe-answers",
            "let": {answerIds: "$answers"},
            "pipeline": [
                { "$match": { "$expr": { "$in": [ "$_id", "$$answerIds" ] } } },
                {$lookup: { from: "users", localField: "createdBy", foreignField: "_id", as: "createdBy" }},
                {"$unwind": {"path": "$createdBy","preserveNullAndEmptyArrays": true} }
                
            ],
            "as": "answers"
        }    
    },
])

This will produce the expected output

answers = [
 { _id,
  content
  createdBy{
     _id
     firstname
     lastname
  }
 },
 { _id,
  content
  createdBy{
     _id
     firstname
     lastname
  }
 }
]
Sign up to request clarification or add additional context in comments.

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.