Mongoose - Increment with findOne

I am working on some query with Mongoose, where I need to skip and limit the attached documents, but in the same query I want to increase the number of fields in the document. Currently, my request is built with a chain, because I had a big problem when I tried to do this only with options. This is what I have:

Model.findOne({ shorten_id: id }).select('title content comments views').slice('comments', [0, 10]).exec(function(err, db_res) { if (err) { throw err; } else { console.log(db_res); } }); 

I would like to increase the number of views of '1' when calling this query, but as I said, I tried a lot of things and it just didn't work.

+6
source share
1 answer

You can use findOneAndUpdate to modify the document as well as extract it.

 Model.findOneAndUpdate({ shorten_id: id }, { $inc: { fieldToIncrement: 1 }) .select('title content comments views') .slice('comments', [0, 10]) .exec(function(err, db_res) { if (err) { throw err; } else { console.log(db_res); } }); 
+14
source

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


All Articles