What parameters are passed to Mongoose callbacks

2019-01-28 00:04发布

问题:

In the mongoose documentation it frequently lists an optional callback for certain query operators (like findOneAndUpdate), however, it does not mention what parameters (arguments) the callback takes. What are they, and how would I find out?

Also, if conditions, update etc. are optional, and I want to specify a callback at the end, do I have to pass in the null value, or empty objects or can I just specify the callback -- and hose does Mongoose know?

Model.findOneAndUpdate([conditions], [update], [options], [callback])

回答1:

For nearly all mongoose queries the provided callback function will be called with two arguments in the node callback pattern callback(err, results) as stated in the documentation:

Anywhere a callback is passed to a query in Mongoose, the callback follows the pattern callback(error, results). What results is depends on the operation: For findOne() it is a potentially-null single document, find() a list of documents, count() the number of documents, update() the number of documents affected, etc. The API docs for Models provide more detail on what is passed to the callbacks.



回答2:

By default you can get two parameters in the callback function: err and results. The first one contains any errors that occurred during the runtime and the second has the old value of document. However you can get other variables in the callback parameters if you set some options in the findOneAndUpdate method. Let's see this with an example:

Model.findOneAndUpdate(
    { id: id_var },
    { $set: { name: name_var } },
    {new: true, passRawResult: true},
    (err, doc, raw) => { /*Do something here*/ })

In this case, the new: true option indicates that the doc variable contains the new updated object. The passRawResult: true option indicates that you can get the raw result of the MongoDB driver as the third callback parameter. The raw parameter contains the result of the update, something like this:

"raw": {
    "lastErrorObject": {
      "updatedExisting": true,
      "n": 1
    },
    "value": { /*the result object goes here*/},
    "ok": 1,
    "_kareemIgnore": true
}


回答3:

According to the official mongoose documentation you can call findOneAndUpdate like this

query.findOneAndUpdate(conditions, update, options, callback) // executes
query.findOneAndUpdate(conditions, update, options)  // returns Query
query.findOneAndUpdate(conditions, update, callback) // executes
query.findOneAndUpdate(conditions, update)           // returns Query
query.findOneAndUpdate(update, callback)             // returns Query
query.findOneAndUpdate(update)                       // returns Query
query.findOneAndUpdate(callback)                     // executes
query.findOneAndUpdate()                             // returns Query

So you can just pass your callback, no need to pass null for other parameters

http://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate