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"
}
}
},
])
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
I wanted to sum likeLength values in all Post collections filtered by postedBy field and get the summed result which type of integer. I tried totalLikes function above but could not make it.
CodePudding user response:
Maybe this can help
- make the string
req.profile._id
to ObjectId - group by
null
all are from the samepostedBy
so all document that passed are in group. (group by null means all collection 1 group) (your group was ok also but this is simpler) - unset the
_id
to get as result[{"total_count" : 20}]
for example
*before testing the group test if $match
works and documents are found.
let totalLikes = Post.aggregate([{
$match: {
postedBy: mongoose.Types.ObjectId(req.profile._id),
}
},
{
$group: {
_id: null,
total_count: {
$sum: "$likeLength"
}
}
},
{"$unset": ["_id"]}
])
CodePudding user response:
The solution for that is the following. With result[0] the result will be an object with sumLikes property.
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])
}})
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>