Mongoose中如何对集合指定字段值求和 筛选Post文档计算likeLength总和
你的代码存在三处核心问题导致无法得到预期结果:
- 第一是Schema定义语法错误:
text、postedBy字段末尾缺少逗号,会导致Schema初始化失败,数据写入/查询都会异常。 - 第二是Mongoose的
aggregate方法是异步API,你直接赋值拿到的是Promise对象而非查询结果,且聚合返回的结果是数组结构,需要手动提取求和值。 - 第三是如果
req.profile._id是字符串格式,需要转成ObjectId类型才能正确匹配_id字段。
修正步骤
- 先修正Schema的语法错误:
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 } });
- 编写正确的聚合查询代码:
// 异步函数内使用await写法 async function getTotalLikes(userId) { const aggregateResult = await Post.aggregate([ { $match: { // 字符串id转ObjectId确保匹配正确 postedBy: mongoose.Types.ObjectId(userId), }, }, { $group: { _id: null, // 所有匹配结果统一分组,不需要按postedBy拆分 total_count: { $sum: "$likeLength" } } }, ]).exec(); // 无匹配文档时默认返回0,确保结果为整数 return parseInt(aggregateResult[0]?.total_count || 0, 10); } // 调用示例 const totalLikes = await getTotalLikes(req.profile._id);
如果你需要同时查询多个用户的总点赞数、按用户分组返回结果,把_id: null改为_id: "$postedBy"即可,遍历返回的结果数组就能拿到对应用户的总点赞数。
内容的提问来源于stack exchange,提问作者jdee
相关产品推荐
相关产品推荐

