'Increment value in update query mongoDB

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

This the function im using:

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)  
});

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.



Solution 1:[1]

You can use $inc to increment the existing value

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

Solution 2:[2]

You could either use $inc

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

Or save the document after updating it

Equipa.findOne({ '_id': req.params.equipaID }, (err, equipa) => {
    equipa.distanciaTotal += req.body.distanciaPercorrida;
    equipa.save();
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kirill Husiatyn
Solution 2 7hibault