How to increase the value of Number in Mongoose?

People StackOverflow, I am burning the question, how to increase the Numerical value in Mongoose? I tried the code below, although it does not work. I am trying to increase the value by one when presenting the 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!

+12
source share
2 answers

You can use $incfor this purpose.

Try the following:

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

For more information about $ inc, please read the MongoDB $ inc documentation

+36
source
Meme.findOneAndUpdate({ _id: res._id }, { $inc: {'post.like': 1 } }, {new: true },function(err, response) {
 if (err) {
 callback(err);
} else {
 callback(response);
}

I hope this link helps you find a solution.

+2
source

Source: https://habr.com/ru/post/1665613/


All Articles