how to get the return value of findAndModify func

2020-07-09 09:20发布

问题:

I'm using Node.js+mongoose+MongoDB like this:

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 the new value of amount without doing the query again. Is there any way to do that?

回答1:

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).



回答2:

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.