const PostSchema = new mongoose.Schema({
title: {
type: String,
},
text: {
type: String,
required: true,
}
postedBy: {
type: mongoose.Schema.ObjectId,
ref: "User",
}
likes: [{
type: mongoose.Schema.ObjectId,
ref: "User",
}, ],
likeLength: {
type: Number,
default: 0
}
});
let totalLikes = Post.aggregate([{
$match: {
postedBy: req.profile._id,
},
},
{
$group: {
_id: "$postedBy",
total_count: {
$sum: "$likeLength"
}
}
},
])
我想對由postedBy 欄位過濾的所有Post 集合中的likeLength 值求和,并獲得哪種型別的整數的求和結果。我嘗試了上面的 totalLikes 函式,但無法實作。
uj5u.com熱心網友回復:
也許這可以幫助
- 將字串
req.profile._id設為 ObjectId - group by
nullall 來自同一個postedBy所以所有通過的檔案都在組中。(group by null 表示所有集合 1 組)(您的組也可以,但這更簡單) - 取消設定
_id,以獲得盡可能結果[{"total_count" : 20}]例如
*在測驗之前小組測驗是否$match找到了作品和檔案。
let totalLikes = Post.aggregate([{
$match: {
postedBy: mongoose.Types.ObjectId(req.profile._id),
}
},
{
$group: {
_id: null,
total_count: {
$sum: "$likeLength"
}
}
},
{"$unset": ["_id"]}
])
uj5u.com熱心網友回復:
解決方案如下。使用 result[0] 結果將是一個具有 sumLikes 屬性的物件。
aggregate([
{
$match: {postedBy: req.profile._id}
},
{
$group: {
_id: null,
sumLikes: {
$sum: "$likeLength",
},
},
},
{ $unset: ["_id"] },
], function(err, result) {
if(err){
console.log(err)
}else{
res.json(result[0])
}})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/364661.html
標籤:javascript 节点.js MongoDB 猫鼬
上一篇:express應用中的所有路由串列(express-promise-router)
下一篇:將二維陣列分配為結構成員
