Mongoose如何保存回调功能?

Mel*_*ssa 13 javascript mongoose mongodb node.js mean-stack

对于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
Run Code Online (Sandbox Code Playgroud)

我如何知道可选回调中的参数?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.
Run Code Online (Sandbox Code Playgroud)

我认为API应该说的可选回调如下:

[fn] <Function> optional callback with this structure:

     function(err, theDocumentToBeSaved, [isSaveSuccessful])
Run Code Online (Sandbox Code Playgroud)

它可以像下面这样使用.请注意,第二个参数(文档)必须与调用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
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我的解释是正确的,那么应该如何构建保存回调参数?

Dro*_*own 27

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

  • 错误
  • 已保存的文档
  • 受影响的行数

这些参数列在这里

请注意,第二个参数(文档)必须与调用save的文档相同

您可以根据需要为参数命名,但不是将其强制转换为对象或类似的东西.它只是一个名称,您希望在其函数体中引用它.