我有一個“社交媒體如帖子”(稱為 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 個小時也找不到解決方案。任何能將我指向甚至遠離當前方向的東西都會有所幫助。
我不想將整個評論陣列加載到記憶體中只是為了獲取嵌套的 likeBy 陣列的長度。否則這甚至都不是問題。
uj5u.com熱心網友回復:
如果您想從所有人中獲得喜歡的總數,comments您可以使用$reduce運算子:
{
$project: {
likes: {
$reduce: {
input: "$comments",
initialValue: 0,
in: { $add: [ "$$value", { $size: "$$this.likedBy" } ] }
}
}
}
}
蒙戈游樂場
或者,您可能需要$map用許多喜歡來豐富每個評論:
{
$project: {
comments: {
$map: {
input: "$comments",
in: {
$mergeObjects: [
"$$this",
{ $numberOfLikes: { $size: "$$this.likedBy" } }
]
}
}
}
}
}
蒙戈游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/372909.html
標籤:javascript 节点.js MongoDB 猫鼬 nosql
上一篇:展平MongoDB嵌套物件
