2
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?

0

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.