Mongoose's如何保存回调工作

How does Mongoose's save callback work?

本文关键字:保存 回调 工作 何保存 Mongoose      更新时间:2023-09-26

对于MEAN堆栈,我正在学习Mongoose的save()函数,该函数接受回调。它的API状态:

Model#save([options], [fn])
Saves this document.
Parameters:
[options] <Object> options set `options.safe` to override [schema's safe option](http://mongoosejs.com//docs/guide.html#safe)
[fn] <Function> optional callback

我如何知道可选回调中有哪些参数?这个API仅仅给出了一个例子:

product.sold = Date.now();
product.save(function (err, product, numAffected) {
  if (err) ..
})
The callback will receive three parameters
err if an error occurred
product which is the saved product
numAffected will be 1 when the document was successfully persisted to MongoDB, otherwise 0.

关于可选回调,我认为API应该这样说:

[fn] <Function> optional callback with this structure:
     function(err, theDocumentToBeSaved, [isSaveSuccessful])

,它可以像下面这样使用。注意,第二个参数document必须与调用save的文档相同。(让我知道如果不是这样。)

documentFoo.save(function(err, documentFoo, [isSaveSuccessful]){
    if(err){ return next(err); }
    if (isSaveSuccessful === 1){
        // documentFoo has been saved correctly 
        // do stuff with the saved documentFoo
    }
}

如果我的解释是正确的,那么保存回调参数应该始终是结构化的吗?

save函数的回调将接受三个参数:

  • 已保存的文件
  • 受影响的行数

参数列在这里

注意,第二个参数document必须与调用save

的文档相同。

你可以随心所欲地命名参数,而不是将其强制转换为对象或类似的东西。它只是一个名称,您希望使用它在函数体中引用它。