Mongoose的保存callback是如何工作的?

对于MEAN堆栈,我正在学习Mongoose的save()函数,它需要callback。 其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 

如何知道可选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应该对可选callback进行说明如下:

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

它可以像下面一样使用。 请注意,第二个参数(文档)必须是调用保存的文档。 (让我知道如果不是这样的话)

 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 } } 

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

savefunction的callback将接受三个参数:

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

参数在这里列出

请注意,第二个参数,即文档必须是调用保存的文档

你可以根据需要命名参数,而不是将其转换为对象或类似的东西。 这只是一个你想用来在你的函数体内引用它的名字。