How to get findAndModify func return value in MongoDB using mongoose?

I am using Node.js + mongoose + MongoDB as follows:

SomeModelSchema.statics.findAndModify = function (query, sort, doc, options, callback) { return this.collection.findAndModify(query, sort, doc, options, callback); }; SomeModel.findAndModify({}, [], { $inc: { amount: 1 } }, {}, function (err) { if (err) throw err; }); 

I can increase the amount successfully, but I want to get a new amount value without having to run the request again. Is there any way to do this?

+7
source share
2 answers

Specify {new:true} in the options object. This will cause the result of the findAndModify result findAndModify become a document after applying the update, which you can then read to get the new amount value.

Details are in the table: http://www.mongodb.org/display/DOCS/findAndModify+Command

I believe that your callback will have to take two arguments, for example: function(err, result){

When the callback is launched, result must contain a new document (if err is null).

+8
source

I checked the monk's source code and finally did it. Even the code documentation says how it should be, but it is not visible from the documentation on the coin.

 /** * findAndModify * * @param {Object} search query, or { query, update } object * @param {Object} optional, update object * @param {Object|String|Array} optional, options or fields * @param {Function} callback * @return {Promise} * @api public */ 

This means that you can specify the request and update as separate parameters, as well as options as the third parameter:

 notescollection.findAndModify( { "_id": id }, { "$set": { "title": title, "content": content }}, { "new": true, "upsert": true }, function(err,doc) { if (err) throw err; console.log( doc ); } ); 

Or you can specify the request and update as the fields of the first parameter, as well as parameters as the second parameter:

 notescollection.findAndModify( { "query": { "_id": id }, "update": { "$set": { "title": title, "content": content }} }, { "new": true, "upsert": true }, function(err,doc) { if (err) throw err; console.log( doc ); } ); 

For more information about sources, check findAndModify in the collections.js file.

+2
source

All Articles