Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I increment a Number value in Mongoose?

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!

like image 815
Safal R. Aryal Avatar asked Jan 03 '17 13:01

Safal R. Aryal


People also ask

What is Mongoose auto increment?

Mongoose plugin that auto-increments any ID field on your schema every time a document is saved. This is the module used by mongoose-simpledb to increment Number IDs. You are perfectly able to use this module by itself if you would like.

What is __ V 0 in Mongoose?

The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero ( __v:0 ).

What is findById in Mongoose?

In MongoDB, all documents are unique because of the _id field or path that MongoDB uses to automatically create a new document. For this reason, finding a document is easy with Mongoose. To find a document using its _id field, we use the findById() function.

Does Mongoose auto generate ID?

_id field is auto generated by Mongoose and gets attached to the Model, and at the time of saving/inserting the document into MongoDB, MongoDB will use that unique _id field which was generated by Mongoose.

What is third parameter in Mongoose model?

ref is part of Mongoose's support for reference population. The third parameter to mongoose. model is an explicit collection name.


2 Answers

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

like image 79
Ravi Shankar Bharti Avatar answered Oct 14 '22 00:10

Ravi Shankar Bharti


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

like image 41
palugu Avatar answered Oct 14 '22 00:10

palugu