猫鼬聚合反向查找或不带localField的查找

时间:2020-08-11 18:10:30

标签: node.js mongoose aggregation mongoose-populate

我想在计划架构上运行聚合并获取一个具有参考ID planId的反馈。 但是,如果我想填充查找内容,则需要在计划中添加参考ID,但是我不喜欢这种保存参考ID的策略,我喜欢将所有内容分开。

有没有引用ID的填充方法?

类似的东西。但这不起作用。

const pipe = [
{
  $lookup: {
    from: 'Feedbacks',
    pipeline: [
      { 
        $match: { 
          planId: '$_id'
        }
      }
    ],
    as: 'feedback'
  }
}]
await Plan.aggregate(pipe);
export interface Plan {
  _id: ObjectId;
  ...

}
export interface Feedback {
  planId: ObjectId;
  ...
}

1 个答案:

答案 0 :(得分:0)

我找到了答案。对于其他任何人:

{
  from: 'Feedbacks',
  let: { planIdInPlan:"$_id"},
  pipeline: [
              {
                $match: {
                  $expr:
                  {
                    $eq:['$planId', '$$planIdInPlan'] 
                  }
                }
                }
            ],
  as: 'feedback'
}