Javascript Mongoose 的保存回调是如何工作的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33019804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:31:13  来源:igfitidea点击:

How does Mongoose's save callback work?

javascriptnode.jsmongodbmongoosemean-stack

提问by Melissa

For the MEAN stack, I'm learning about Mongoose's save() function, which takes a callback. Its API states:

对于 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

How do I know what arguments are in the optional callback? The API merely gives an example:

我怎么知道可选回调中有哪些参数?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.


What I think the API should say about the optional callback is the following:

我认为 API 应该说的关于可选回调的内容如下:

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

     function(err, theDocumentToBeSaved, [isSaveSuccessful])

and it can be used like the following. Note that the second argument, the document, must be the same document that is calling the save.(Let me know if it's not the case.)

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

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

If my interpretation is correct, is that how the save callback parameters should always be structured?

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

回答by Drown

The savefunction's callback will accept three arguments :

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

  • The error
  • The document that was saved
  • The number of rows affected
  • 错误
  • 保存的文档
  • 受影响的行数

The arguments are listed here

这里列出参数

Note that the second argument, the document, must be the same document that is calling the save

请注意,第二个参数,即文档,必须是调用 save 的同一个文档

You can name the arguments however you want, you're not casting it to an object or anything like that. It's simply a name that you want to use to refer it to in your function's body.

您可以随意命名参数,而不是将其转换为对象或类似的东西。它只是一个您想用来在函数体中引用它的名称。