【发布时间】:2022-01-10 16:45:29
【问题描述】:
我有一个“类似帖子的社交媒体”的猫鼬模型(称为 PostModel),它具有以下架构:
{
caption: String,
comments: [
{
comment: String,
// basically an array to store all those who liked the comment
likedBy: [...] // array of references to a different model
},
... // more comment objects like this
]
}
我只是想知道在查询帖子时每条评论获得的点赞数。这不应该像现在这样烦人和困难。我在这上面花了 4 个多小时。
到目前为止我所尝试的:
尝试 1:
PostModel.findById(postId, {
"comments.likes": { $size: "$comment.likedBy" } // gives the number of comments instead of the number of likes on the comment
})
尝试 2:
PostModel.findById(postId, {
"comments.likes": { $size: "$likedBy" } // gives "likedBy not defined" error
})
尝试 3:
PostModel.findById(postId, {
"comments.likes": { $size: "$comments.$likedBy" } // gives "FieldPath field names may not start with '$'. Consider using $getField or $setField" error
})
尝试 4:
PostModel.findById(postId, {
"comments.likes": { $size: "$comments.$.likedBy" } // gives "FieldPath field names may not start with '$'. Consider using $getField or $setField" error
})
我基本上想在这个“forEach”之类的数组遍历中访问“当前元素”。例如:
const a = [{likes: ["x", "y"]}, {likes: ["a", "b"]}, {likes: []}];
a.forEach((element, index) => {
console.log(element.likes.length) // this is what I want but for mongoDB
})
// output: 2 2 0
我到处寻找,但即使搜索了 4 个小时也找不到解决方案。任何能让我远离当前方向的东西都会有所帮助。
我不想将整个 cmets 数组加载到内存中,只是为了获取嵌套 likeBy 数组的长度。否则这甚至都不是问题。
【问题讨论】:
标签: javascript node.js mongodb mongoose nosql