【问题标题】:Mongoose error handling with Promises使用 Promises 处理 Mongoose 错误
【发布时间】:2017-01-11 19:15:21
【问题描述】:

我在我的 Nodejs REST API 中使用带有原生 ES6 承诺的 mongoose 进行数据库管理。

我无法找到有关错误处理的最佳做法。我有一段代码如下所示:

Cities.findOne({'id': someid}).then((city) => {
  if (!city) throw 'No city found';
  //modify city.embedded.dynamic.field
  return city.save();
}).then((city) => {
  if (!city) throw 'City not saved';
  res.send(city);
}).catch((err) => {
  console.log(err);
});

我是否需要检查city.save() 的返回是否未定义?或者保存中的错误是否会被捕获?

文档中不清楚save() 是否可以像猫鼬查询有时那样返回undefined

任何帮助将不胜感激。

编辑:我正在使用 findOne 并手动修改计划,因为 mongoose 无法对动态和嵌入的模式进行建模。

【问题讨论】:

    标签: javascript node.js mongoose promise es6-promise


    【解决方案1】:

    findOne() 返回一个承诺。返回结果时为resolved,无论是否为空。发生错误时是rejected。任何find() 的空结果将是null,而不是undefined

    如果您尝试保存的元素不存在,您将收到 [TypeError: Cannot read property 'save' of null]

    但是,您可以使这更简单:

    return Cities.findByIdAndUpdate(city._id, {$set:city}, {new: true} ).exec()
                 .then( (city) => { res.send(city) } )
    

    将选项new 设置为true 使函数返回元素更新后,而不是更新之前

    【讨论】:

    • findByIdAndUpdate 可以很好地工作,但我不能使用它:((在我的问题中添加了编辑)。我担心的部分是 model#save 是否有可能失败并且仍然有它的承诺resolved
    【解决方案2】:

    Mongoose Promise 使用 callback(error, result){} 机制,该机制遵循暴露的 crud 函数,例如 newElement.save( function( err, result){} )。如果出现任何错误,promise 就会被拒绝,这就是逻辑。

    【讨论】:

      猜你喜欢
      • 2014-05-27
      • 2016-11-05
      • 1970-01-01
      • 2018-10-26
      • 2014-07-03
      • 2019-01-15
      • 2012-08-05
      • 2014-01-07
      • 2012-12-28
      相关资源
      最近更新 更多