MongoDB Lookup Returns an empty array, only when there is no data

Viewed 639
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);

I have this code. What is wrong about with this code is;

  • If altComments is empty, then returns an empty array even if there is a data. If i add alt comment data to any comment then response is correct.

How can i solve this? What am i doing wrong?

1 Answers

The reason is $unwind. Unwind default behaviour of preserveNullAndEmptyArrays is false. Which means in short is if the array is empty or null, remove the document when deconstructing. If you dont need to remove, you can make it as true. So when your array doesn't have any element, the document is removed. Thats you you are getting empty array

$Unwind documentation

Related