增加mongoDB中的值 [英] Increment value in mongoDB

查看:99
本文介绍了增加mongoDB中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在mongoose函数中添加两个值。

I am trying to add two values in a mongoose function.

这个函数即时使用:

Equipa.findOne({ '_id': req.params.equipaID }, function (error, equipa) {
  if (error) {
    return (error);
  }

  if (util.isNullOrUndefined(equipa)) {
    return res.status(204).end()
  }

  console.log(equipa.distanciaTotal + "------" + req.body.distanciaPercorrida),
  { total : {$add[equipa.distanciaTotal,req.body.distanciaPercorrida]}},
  console.log(total)  
});

equipa.distanciaTotal req.body.distanciaPercorrida 是正确的, Equipa.findOne <找到 Equipa / code>。

The values in equipa.distanciaTotal and req.body.distanciaPercorrida are correct, and so is the Equipa found by Equipa.findOne.

我认为更新文档会很好,但我根本无法添加这两个值。

I think it will be fine updating the document, but I simply cannot add the two values.

推荐答案

你可以使用 $ inc 增加现有价值

You can use $inc to increment the existing value

Equipa.findOneAndUpdate(
  { '_id': req.params.equipaID },
  { '$inc': {
    distanciaTotal: req.body.distanciaPercorrida }
  }
)

这篇关于增加mongoDB中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆