What parameters are passed to Mongoose callbacks

前端 未结 3 1473
没有蜡笔的小新
没有蜡笔的小新 2020-12-11 16:55

In the mongoose documentation it frequently lists an optional callback for certain query operators (like findOneAndUpdate), however, it does not mention what pa

相关标签:
3条回答
  • 2020-12-11 17:20

    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
    }
    
    0 讨论(0)
  • 2020-12-11 17:32

    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.

    0 讨论(0)
  • 2020-12-11 17:40

    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

    0 讨论(0)
提交回复
热议问题