[英]MongoDB Aggregation.. Counting inside an array on produce the output on javascript. using nodeJS, mongoose
這是我的貓鼬圖式
var testSchema = new mongoose.Schema({
name: String,
image: String,
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}
]
});
所以每個用戶都有名字,圖片和評論。 注釋是數組。 基本上我有10個用戶,有不同的評論,我想計算每個用戶有多少評論並顯示在html上。
我已經試過了
db.users.aggregate({$project: { count: {$size:"$comments"}}})
它計算所有用戶的每個用戶的評論...我如何在html上輸出它? 以及如何僅對1個用戶執行此命令? 並非所有用戶...謝謝!
要查找單個用戶發表的評論數量,請在貓鼬中使用以下命令。
Users.findOne({_id: ObjectId("57cdf6b3fbccf41198389aca")}, function(err, user) {
if(err) {
//handle error
} else if(!user) {
//no user found
} else {
//user found
if(user.comments) {
console.log('user comments length', user.comments.length);
} else {
console.log('no user comments');
}
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.