【问题标题】:What parameters are passed to Mongoose callbacks什么参数被传递给 Mongoose 回调
【发布时间】:2015-06-15 23:52:20
【问题描述】:

mongoose documentation 中,它经常列出某些查询运算符(如findOneAndUpdate)的可选回调,但是,它没有提及回调采用哪些参数(参数)。它们是什么,我该如何发现?

另外,如果conditionsupdate 等是可选的,并且我想在最后指定一个回调,我必须传入null 值,还是空对象,或者我可以只指定回调——猫鼬知道吗?

Model.findOneAndUpdate([conditions], [update], [options], [callback])

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

默认可以在回调函数中获取两个参数:errresults。第一个包含运行时发生的任何错误,第二个包含文档的旧值。但是,如果您在 findOneAndUpdate 方法中设置了一些选项,则可以在回调参数中获取其他变量。让我们看一个例子:

Model.findOneAndUpdate(
    { id: id_var },
    { $set: { name: name_var } },
    {new: true, passRawResult: true},
    (err, doc, raw) => { /*Do something here*/ })

在这种情况下,new: true 选项表示 doc 变量包含新更新的对象。 passRawResult: true 选项表示您可以获取 MongoDB 驱动程序的原始结果作为第三个回调参数。 raw 参数包含更新的结果,如下所示:

"raw": {
    "lastErrorObject": {
      "updatedExisting": true,
      "n": 1
    },
    "value": { /*the result object goes here*/},
    "ok": 1,
    "_kareemIgnore": true
}

【讨论】:

    【解决方案2】:

    对于几乎所有mongoose queries,所提供的callback 函数将在node callback pattern callback(err, results) 中使用两个参数调用,如文档中所述:

    在 Mongoose 中将回调传递给查询的任何地方,回调都遵循callback(error, results) 模式。结果取决于操作:对于findOne(),它是potentially-null single documentfind()list of documentscount()number of documentsupdate()number of documents affected 等。API docs for Models 提供有关传递给回调的内容的更多详细信息。

    【讨论】:

      【解决方案3】:

      根据官方 mongoose 文档,您可以像这样调用 findOneAndUpdate

      query.findOneAndUpdate(conditions, update, options, callback) // executes
      query.findOneAndUpdate(conditions, update, options)  // returns Query
      query.findOneAndUpdate(conditions, update, callback) // executes
      query.findOneAndUpdate(conditions, update)           // returns Query
      query.findOneAndUpdate(update, callback)             // returns Query
      query.findOneAndUpdate(update)                       // returns Query
      query.findOneAndUpdate(callback)                     // executes
      query.findOneAndUpdate()                             // returns Query
      

      所以你可以只传递你的回调,不需要为其他参数传递 null

      http://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate

      【讨论】:

        猜你喜欢
        • 2019-10-07
        • 1970-01-01
        • 2016-12-09
        • 1970-01-01
        • 2015-04-08
        • 2018-04-29
        • 2022-12-24
        • 1970-01-01
        相关资源
        最近更新 更多