【问题标题】:MongoDB Lookup Returns an empty array, only when there is no dataMongoDB Lookup 返回一个空数组,只有在没有数据的时候
【发布时间】:2021-03-19 01:11:27
【问题描述】:
let CommentsList = Comment.aggregate()
        .lookup({
            from: "users",
            localField: "user",
            foreignField: "sid",
            as: "userInfo"
        })
        .unwind("$userInfo")
        .addFields({
            "comId": { "$toString": "$_id"}
        })
        .lookup({
            from: "alt_comments",
            localField: "comId",
            foreignField: "commentId",
            as: "altComments"
        })
        .unwind("$altComments")
        .group({
            "_id": "$_id",
            "username": { "$first": "$userInfo.username" },
            "avatar": { "$first": "$userInfo.avatar" },
            "content": { "$first": "$comment" },
            "likeCount": { "$first": "$likeCount" },
            "likedUsers": { "$first": "$likedUsers" },
            "unlikeCount": { "$first": "$unlikeCount" },
            "unlikedUsers": { "$first": "$unlikedUsers" },
            "avgCount": { "$first": "$avgCount" },
            "type": { "$first": "$type" },
            "slug": { "$first": "$slug" },
            "sendDate": { "$first": "$sendDate" },
            "starter": { "$first": "$user" },
            "altComments": { "$push": "$altComments"}
        })
        .match({"slug": req.query.slug, "type": req.query.type})
        .sort({ sendDate: -1 })
        .skip(10 * req.query.page)
        .limit(10);

我有这个代码。这段代码有什么问题;

  • 如果 altComments 为空,则即使有数据也返回一个空数组。如果我将 alt 评论数据添加到任何评论,则响应是正确的。

我该如何解决这个问题?我做错了什么?

【问题讨论】:

    标签: mongodb express mongoose aggregate lookup


    【解决方案1】:

    原因是$unwindpreserveNullAndEmptyArrays 的展开默认行为是 false。简而言之,如果数组为空或 null,则在解构时删除文档。如果不需要删除,可以设为true。因此,当您的数组没有任何元素时,文档将被删除。那就是你得到空数组

    $Unwind documentation

    【讨论】:

      猜你喜欢
      • 2018-08-27
      • 2019-04-15
      • 2021-11-16
      • 2017-11-01
      • 1970-01-01
      • 2018-07-26
      • 2018-02-03
      相关资源
      最近更新 更多