【发布时间】:2021-04-01 00:29:01
【问题描述】:
I have photos with an array of likes. I am using mongoose as a db. I want to sum all the numeric values in the likes count of photo collection.
exports.getAnalytics = (req, res) => {
if (!req.user) {
return res.redirect('/login');
}
Campaign.findOne({slug:req.params.slug}, (err, campaign) => {
PhotoEntries.find({ CampaignId: campaign._id}, ['Photo','Name', 'done' ,'likes_count', ], {sort:{ _id: -1} }, function(err, photos) {
PhotoEntries.countDocuments({CampaignId: campaign._id} , function (err, count) {
PhotoEntries.aggregate([
{
$group: {
_id: "$CampaignId",
Totallikes: { $sum: "$likes_count" }
}
}
])
if(req.user){
console.log(photos);
res.render('admin/analytics', {
title: 'Analytics',
campaign: campaign,
photolist : photos,
Count:count ,
Totallikes: Totallikes
});
}
// }
// ])
});
});
});
}
但是它不起作用。错误是Arguments must be aggregate pipeline operators. 我怎样才能做到这一点?
这是我的架构代码。
var photoSchema = 新架构({
名称:{类型:字符串},
电子邮件:{类型:字符串},
照片:{类型:字符串},
说明:{类型:字符串},
电话号码:{类型:字符串},
活动 ID:{
类型:Schema.Types.ObjectId,
ref: '广告系列',
},
done: {
type: Boolean ,
},
likes_count: Number ,default: 0,
likedBy: [
{
type:Schema.Types.ObjectId,
ref: "User"
}
],
});
}
我需要将likes_count 字段添加到集合中的所有文档中。
【问题讨论】:
-
您能否在您的问题和预期结果中添加照片集架构。
-
你想做什么?您需要在集合中添加新字段吗?还是只需要通过聚合进行计数和检索?你的问题不清楚。
-
通过聚合只计算和检索