MongoDB查找Returns一个空数组,只有在没有数据的时候
MongoDB Lookup Returns an empty array, only when there is no data
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 为空,则 returns 即使有数据也是一个空数组。如果我将 alt 评论数据添加到任何评论,则响应是正确的。
我该如何解决这个问题?我做错了什么?
原因是$unwind
。 preserveNullAndEmptyArrays
的展开默认行为是 false
。简而言之,如果数组为空或 null,则在解构时删除文档。如果不需要删除,可以将其设置为true
。因此,当您的数组没有任何元素时,文档将被删除。那就是你得到的是空数组
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 为空,则 returns 即使有数据也是一个空数组。如果我将 alt 评论数据添加到任何评论,则响应是正确的。
我该如何解决这个问题?我做错了什么?
原因是$unwind
。 preserveNullAndEmptyArrays
的展开默认行为是 false
。简而言之,如果数组为空或 null,则在解构时删除文档。如果不需要删除,可以将其设置为true
。因此,当您的数组没有任何元素时,文档将被删除。那就是你得到的是空数组