Jamie Hutber
Jamie Hutber

Reputation: 28096

Adding to existing value with findOneAndUpdate MongoDB

I would like to be able to do maths in my query without having to first pull down the data from the db, doing the maths then passing the object to the findOneAndUpdate

Model

var Player = new Schema({
     goals: {type: Number, default: 2}
});

Update

var updatedPlayers = {goals:2};

return Player.findOneAndUpdate(user_id, updatedPlayers, function (err, doc) {
    if (err) return res.send(500, {error: err});
    return doc;
})

Desired Outcome of a find on the player

{goals: 4}

Upvotes: 7

Views: 4811

Answers (1)

vmkcom
vmkcom

Reputation: 1668

You need to use MongoDB $incupdate operator

return Player.findOneAndUpdate(user_id, {$inc: {goals: 2}}, function (err, doc) {
  if (err) return res.send(500, {error: err});
  return doc;
})

So it's increase number of goals by 2 from previous value

Upvotes: 8

Related Questions