You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB写入时如何使用aggregate与$sum?编程新手求助

解决方法:计算请求参数总和并写入MongoDB

首先得帮你理清一个关键误区:你现在用的aggregate是MongoDB针对数据库中已有文档的聚合操作,而你当前的需求是计算这次请求里传入的score1到score4的总和,完全不需要调用数据库的聚合方法,直接在代码里做加法就可以了!

第一步:修正路由里的计算逻辑

你之前的代码里,score5的赋值是错误的——scoresha.aggregate(...)是异步的数据库操作,而且根本不是用来计算内存变量的。正确的做法是把req.body里的参数转换成数字后直接相加:

router.post('/xxxxxxx', function(req, res){
 console.log('function called!!');
 // 先把请求参数转成数字,避免字符串拼接问题
 const score1 = Number(req.body.score1);
 const score2 = Number(req.body.score2);
 const score3 = Number(req.body.score3);
 const score4 = Number(req.body.score4);
 // 直接计算总和
 const score5 = score1 + score2 + score3 + score4;

 // 你的其他变量和验证逻辑保持不变
 req.checkBody('xxxx', 'xxxx').notEmpty();
 req.checkBody('xxxx', 'xxxxxxxx').notEmpty();
 var errors = req.validationErrors();
 if(errors){
  res.render('xxxxxxxxx',{ errors:errors });
 } else {
  console.log('success');
  var newXxxxxx = new xxxxxxxx({
   score1: score1,
   score2: score2,
   score3: score3,
   score4: score4,
   score5: score5,
   // ...其他字段
  });
  // 修正保存逻辑(原代码有笔误,用文档自身的save方法更直观)
  newXxxxxx.save(function(err, savedDoc){
   if(err) throw err;
   console.log('successfully saved');
  });
  req.flash('success_msg', 'Success.');
  res.redirect('/xxxxx/xxxxx');
 }
});
module.exports = router;

第二步:关于逻辑应该放在哪里?

你问应该在Schema、Model还是Route里实现这个逻辑,分两种场景来看:

  • 如果只是单次创建文档时计算总和:放在Route里完全没问题,就像上面的代码这样,简单直接。
  • 如果需要每次文档更新(比如修改score1-4时)自动更新score5:那更推荐把逻辑放在Schema的pre-save中间件里,这样不管是创建还是更新,都会自动计算总和,避免重复写代码。示例如下:
// 在你的Score Schema文件里
const scoreSchema = new mongoose.Schema({
  score1: Number,
  score2: Number,
  score3: Number,
  score4: Number,
  score5: Number,
  // ...其他字段
});

// 添加pre-save中间件,保存前自动计算score5
scoreSchema.pre('save', function(next) {
  // 这里的this指向当前要保存的文档
  this.score5 = this.score1 + this.score2 + this.score3 + this.score4;
  next();
});

const Score = mongoose.model('Score', scoreSchema);
module.exports = Score;

之后不管你在Route里创建还是更新文档,只要修改了score1-4,score5都会自动计算并保存,不用再在Route里重复写求和逻辑。

为什么你的aggregate尝试失败?

再补充说明一下,aggregate是用来对数据库里的多个文档做统计的——比如你想统计所有文档的score1总和,才会用:

Score.aggregate([
  { $group: { _id: null, totalScore1: { $sum: "$score1" } } }
])

但这和你当前计算单个请求里的参数总和完全是两回事,所以用在这里根本不对哦。

内容的提问来源于stack exchange,提问作者Jiikoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:50:03