猫鼬聚合查找管道不起作用

时间:2020-10-07 19:07:36

标签: javascript node.js mongodb mongoose mongoose-populate

有谁知道为什么这种聚合仅匹配帖子,却不填充评论?

我需要评论集合中的用户评论,但只有空管道返回评论

Post.aggregate(...)
[
        {
            "$match": {
                "author": ObjectId(...)
            }
        },
        {
            "$lookup": {
                "from": "comments",
                "let": {
                    "postID": "$post",
                    "isHiden": "$isHiden"
                },
                "pipeline": [
                    {
                        "$match": {
                            "$expr": {
                                "$and": [
                                    {
                                        "$eq": [
                                            "$_id",
                                            "$$postID"
                                        ]
                                    },
                                    {
                                        "$eq": [
                                            "$$isHiden",
                                            0
                                        ]
                                    }
                                ]
                            }
                        }
                    }
                ],
                "as": "comments"
            }
        }
    ]

评论对象包含

{
  "_id": "5f7de8491af5c0e246d42609",
  "isHiden": false,
  "text": "...",
  "post": "5f7de8491af5c0e246d42605"
}

帖子模型是

{
  "_id": "5f7de8491af5c0e246d42605",
  "title": "Corporate Web Coordinator",
  "body": "...",
  "author": "5f7de8491af5c0e246d42602"
  }
}

我想得到像这样的结果

       {
            "_id": "5f7de8491af5c0e246d42605",
            "confirm_status": "pending",
            "title": "Dynamic Marketing Supervisor",
            "body": "...",
            "author": "5f7de8491af5c0e246d42604",
            "comments": [
                  { "_id": "5f7de8491af5c0e246d42609",
                    "isHiden": false,
                    "text": "...",
                    "post": "5f7de8491af5c0e246d42605" }
             ]
        }

我尝试了一切,但无济于事...

我将不胜感激

1 个答案:

答案 0 :(得分:1)

问题出在您的查询中,

  • post字段出现在注释表中,并且您使用了_id,因此应为$post
  • 内部管道字段isHiden在发布表中不存在,您正在let中定义该字段,
    $lookup: {
      from: "comments",
      let: { postID: "$_id" },
      pipeline: [
        {
          $match: {
            $expr: [
              {
                $eq: [
                  "$$postID",
                  "$post"
                ]
              }
            ],
            isHiden: false
          }
        }
      ],
      as: "comments"
    }

Playground