58

People of StackOverflow, I am burning with the question, how do I increment a
Number value in Mongoose? I have tried the code below, though it is not working. I am trying to increment a value by one on the submission of a form. Below is my code:

app.post('/like', function (req, res) {
    var id = req.body.id;
    var query = {_id: id};
    var post = Meme.findOne(query);
    Meme.findOneAndUpdate(post, post.likes: post.likes+1)
});

Thanks so much for your valuable help!

Strider
  • 3,539
  • 5
  • 32
  • 60
Safal R. Aryal
  • 739
  • 1
  • 6
  • 11
  • 3
    you can try something like this `Meme.findOneAndUpdate(query, { $inc: { "post.likes": 1 } })`. Not tested. – s7vr Jan 03 '17 at 13:13
  • Are you getting the data in your `post` variable? Please put a `console` statement and check whether data is coming or not. – Arpit Kumar Jan 03 '17 at 13:14
  • @Safal_R_Aryal you can also refer this question for more information http://stackoverflow.com/questions/8621948/doing-inc-with-mongoose Thanks! – Arpit Kumar Jan 03 '17 at 13:17

4 Answers4

118

You can use $inc for this purpose.

Try this:

var id = req.body.id;
Meme.findOneAndUpdate({_id :id}, {$inc : {'post.likes' : 1}}).exec(...);

For more info on $inc, Please read MongoDB $inc documentation

Ravi Shankar Bharti
  • 8,922
  • 5
  • 28
  • 52
  • 9
    also works if you want to reduce: just give a negative number like so:var id = req.body.id; Meme.findOneAndUpdate({_id :id}, {$inc : {'post.likes' : -1}}).exec(...); – dang Mar 03 '19 at 11:48
11

With mongoose version 5 an additional option "useFindAndModify" is needed:

 // Make Mongoose use mongoDB's `findOneAndUpdate()`. Note that this option is `true`
 // by default, you need to set it to false.
 mongoose.set('useFindAndModify', false);


 Meme.findOneAndUpdate( {_id: res._id}, 
      {$inc : {'UID' : 1}}, 
      {new: true}, 
      function(err, response) { 
           // do something
      });

Mongoose Depreciation Doc

dexbyte
  • 65
  • 11
palugu
  • 111
  • 1
  • 4
5
Meme.findOneAndUpdate({ _id: res._id }, { $inc: {'post.like': 1 } }, {new: true },function(err, response) {
 if (err) {
 callback(err);
} else {
 callback(response);
}

Hope this link help to find your solution

Praveen Gehlot
  • 364
  • 2
  • 11
1

You can also try this, I used this query to like the post

app.put('/like', (req, res) => {
    Meme.findByIdAndUpdate(req.body.postId,{
    $push:{likes: req.user._id}
    }, {
        new: true
    }).exec((err, result) => {
        if(err){
            return res.status(400).json({error: err})
        }else{
            res.json(result)
        }
    })
})
David Buck
  • 3,752
  • 35
  • 31
  • 35
satendra singh
  • 129
  • 1
  • 11