我收集了以下帖子
{
"_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" : []
}
答案 0 :(得分:1)
仅 preserveNullAndEmptyArrays 至 true 默认为false。
{
$unwind: {
path: '$toUserData',
preserveNullAndEmptyArrays: true,
},
},
请参阅链接:https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/