【问题标题】:How does Mongoose's save callback work?Mongoose 的保存回调是如何工作的?
【发布时间】:2016-01-06 07:30:08
【问题描述】:

对于 MEAN 堆栈,我正在学习 Mongoose 的 save() 函数,该函数需要回调。它的API states

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])

它可以像下面这样使用。 请注意,第二个参数,即文档,必须与调用保存的文档相同。(如果不是,请告诉我。)

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

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

【问题讨论】:

    标签: javascript node.js mongodb mongoose mean-stack


    【解决方案1】:

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

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

    参数列在here

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

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

    【讨论】:

      猜你喜欢
      • 2017-08-07
      • 2016-01-11
      • 1970-01-01
      • 2015-06-14
      • 2012-01-22
      • 2013-10-21
      • 1970-01-01
      • 2011-11-20
      • 1970-01-01
      相关资源
      最近更新 更多