how to get the return value of findAndModify func in MongoDB with mongoose? how to get the return value of findAndModify func in MongoDB with mongoose? mongodb mongodb

how to get the return value of findAndModify func in MongoDB with mongoose?


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

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

I believe your callback will need to take two arguments, like:function(err, result){

When the callback is fired, result should contain the new document (if err is null).


I checked monk's source code and finally made this working. Even code documentation says how it should be, but it is not visible from documentation on monk's web.

/** * 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 */

It means you can either specify query and update as separate parameters, plus options as 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 query and update as fields of first parameter, plus options as 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 on the sources check findAndModify function in collections.js file.