Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose - Increment with findOne

I'm working on some query with Mongoose where I need to skip and limit subdocuments, but in the same query I want to increment some field in document. Currently is my query built with chaining, because I got a lot of problem when I tried to do it just 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 increment filed 'views' for 1 when calling this query, but as I said, I tried a lot of things and it just didn't work.

like image 499
user1257255 Avatar asked May 03 '13 09:05

user1257255


1 Answers

You can use findOneAndUpdate to modify a document while also fetching one.

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); 
    } 
  });
like image 129
matthewtole Avatar answered Oct 25 '22 07:10

matthewtole