哪些参数传递给 Mongoose 回调

What parameters are passed to Mongoose callbacks

mongoose documentation中,它经常为某些查询运算符(如findOneAndUpdate)列出一个可选的回调,但是,它没有提到回调采用什么参数(arguments)。它们是什么,我怎么知道?

另外,如果conditionsupdate等是可选的,我想在最后指定一个回调,是否必须传入null值,或者空对象或者我可以只指定回调 -- Mongoose 知道吗?

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

根据猫鼬官方文档,您可以像这样调用 findOneAndUpdate

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

所以你可以只传递你的回调,不需要为其他参数传递null

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

对于文档中所述的几乎所有 mongoose queries the provided callback function will be called with two arguments in the node callback pattern callback(err, results)

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.

回调函数默认可以获取两个参数:errresults。第一个包含运行时发生的任何错误,第二个包含文档的旧值。但是,如果您在 findOneAndUpdate 方法中设置一些选项,则可以在回调参数中获取其他变量。让我们看一个例子:

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

在这种情况下,new: true 选项表示 doc 变量包含新更新的对象。 passRawResult: true 选项表示您可以获得 MongoDB 驱动程序的原始结果作为第三个回调参数。原始参数包含更新的结果,像这样:

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