如何仅在猫鼬中使用聚合来填充嵌套在对象数组中的字段?

How do I populate a field nested in array of objects using aggregation only in mongoose?

我尝试在数组中填充深度嵌套的对象已经有一段时间了,但没有成功。我尝试展开数组,但生成的数组被转换为对象而不是数组。

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"
            }
            },
            
        ];

预期输出

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

返回的输出

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

上述查询确实填充了 createdBy 字段,但将数组转换为对象。我需要的是在答案数组的每个元素中填充 createdBy 字段。感谢您的帮助。

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"
        }    
    },
])

这将产生预期的输出

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