简体   繁体   English

Mongoose如何保存回调功能?

[英]How does Mongoose's save callback work?

For the MEAN stack, I'm learning about Mongoose's save() function, which takes a callback. 对于MEAN堆栈,我正在学习Mongoose的save()函数,它接受回调。 Its API states : 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. 请注意,第二个参数(文档)必须与调用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? 如果我的解释是正确的,那么应该如何构建保存回调参数?

The save function'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. 它只是一个名称,您希望在其函数体中引用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM