What parameters are passed to Mongoose callbacks

The mongoose documentation often lists an optional callback for specific query operators (e.g. findOneAndUpdate ), however it does not mention that callback parameters (arguments). What are they and how do I know?

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

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

+5
source share
3 answers

For almost all mongoose requests, the provided callback function will be called with two arguments in the node Reverse callback(err, results) template callback(err, results) , as indicated in the documentation:

In any case, the callback is passed to the request in Mongoose, the callback follows the callback(error, results) pattern. What results depend on the operation: for findOne() this is a potentially zero single document , find() a list of documents , count() number of documents , update() a number of affected documents , etc. The API documents for models provide more details on what is passed to callbacks.

+7
source

By default, you can get two parameters in the callback function: err and results . The first contains all errors that occurred at run time, and the second contains the old value of the document. However, you can get other variables in the callback parameters if you set some parameters in the findOneAndUpdate method. Let's look at 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 parameter indicates that the doc variable contains the new updated object. The passRawResult: true option indicates that you can get the original MongoDB driver result as the third callback parameter. The raw parameter contains the update result, something like this:

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

According to mongoose's official documentation, you can call findOneAndUpdate as follows

 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

+1
source

All Articles