Mongoose 的保存回调是如何工作的? [英] How does Mongoose's save callback work?

查看:66
本文介绍了Mongoose 的保存回调是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For the MEAN stack, I'm learning about Mongoose's save() function, which takes a callback. Its 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 只是举例:

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

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

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

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

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

推荐答案

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

The save function's callback will accept three arguments :

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

参数列在此处

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

Note that the second argument, the document, must be the same document that is calling the 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.

这篇关于Mongoose 的保存回调是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆