当嵌套数组为空时,$ lookup和$ unwind不会产生任何结果

时间:2018-05-09 12:35:16

标签: node.js mongodb mongoose mongodb-query aggregation-framework

我收集了以下帖子

{
    "_id" : ObjectId("5ad5ddb15e540442a7d4213c"),
    "content" : "content1",
    "comments" : [ObjectId("5af2a10dc56ad8378a3fbffa")]
}

我有以下评论收集

{
    "_id" : ObjectId("5af2a10dc56ad8378a3fbffa"),
    "likeBy" : [ObjectId("5ac8ba3582c2345af70d4658")],
    "post" : ObjectId("5ad5ddb15e540442a7d4213c"),
    "comment" : "comment1",
}

我做了以下$lookup查询...当评论数组有ids时,查询工作正常

"comments" : [ObjectId("5af2a10dc56ad8378a3fbffa")]

...但是当评论被清空时

    "comments" : []

然后它返回空数组......至少它应该返回第一个match条件{ $match: { _id: mongoose.Types.ObjectId(id) }} ...

const post = await Post.aggregate([
          { $match: { _id: mongoose.Types.ObjectId(id) }},
          { $lookup: {
              from: 'comments',
              localField: 'comments',
              foreignField: '_id',
              as: 'comments'
            }
          },
          { $unwind: '$comments' },
          { $addFields: {
            "comments.isLiked": {
              $in: [ 
                mongoose.Types.ObjectId(req.user.id), 
                "$comments.likeBy"
              ]
            }
          }}
          { $group: {
              _id: '$_id',
              content: {$first: '$content'},
              comments: {$push: '$comments'}
            }
          }
        ])

所以我的预期结果应该是

    {
        "_id" : ObjectId("5ad5ddb15e540442a7d4213c"),
        "content" : "222222222222222222222222222222222222222222",
        "comments" : []
    }

1 个答案:

答案 0 :(得分:1)

preserveNullAndEmptyArrays true 默认为false。

{
      $unwind: {
        path: '$toUserData',
        preserveNullAndEmptyArrays: true,
      },
    },

请参阅链接:https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/