【问题标题】:Mongoose - How can I throw more than one error in pre (save/update) middleware?Mongoose - 如何在预(保存/更新)中间件中抛出多个错误?
【发布时间】:2020-04-22 02:25:47
【问题描述】:

我在模型中有一些预保存和更新钩子,我需要同时显示所有验证错误。

文档中有关于 next 功能的信息:

多次调用 next() 是无操作的。如果调用 next() 报错 err1,然后抛出错误 err2,mongoose 会报 err1。

见参考here

我想做类似下面的代码来返回两个或多个验证错误,但像文档一样只抛出第一个错误

Schema.pre('save', function(next) {
  if (this.prop1 == 'foo')
    next(new Error('Error one'))

  if (this.prop2 == 'bar')
    next(new Error('Error two'))
})

我该怎么做?有其他选择吗?

【问题讨论】:

标签: javascript node.js mongodb mongoose hook


【解决方案1】:

你可以将你的errors添加到一个数组中,最后如果数组的长度大于0,你可以通过加入errors来发送一条错误信息。

Schema.pre("save", function(next) {
  let validationErrors = [];

  if (this.prop1 == "foo") validationErrors.push("Error one");

  if (this.prop2 == "bar") validationErrors.push("Error two");

  if (validationErrors.length > 0) {
    next(new Error(validationErrors.join(",")));
  }

  next();
});

但一般我们不使用这种验证。如果你已经在使用猫鼬,你可以使用它的验证features

其他一些验证包是:

  1. Express Validator
  2. Joi

【讨论】:

  • eheh 你回答的和我写代码时的回答一样,点赞! :D
【解决方案2】:

你好丹尼尔,欢迎来到 Stack Overflow!

我的方法是将错误保存到一个可迭代对象中并将该可迭代对象作为错误对象发送下来(或者如果它只接受字符串,则使用 join() 将整个事情字符串化。

请检查这是否能解决您的问题,我不知道任何实现最终结果的内置方法。

Schema.pre('save', function(next) {
  const errors = [];

  if (this.prop1 == 'foo')
    errors.push('Error one');

  if (this.prop2 == 'bar')
    errors.push('Error two');

  if (this.prop1 == 'foo' || this.prop2 == 'bar') next(new Error(errors))
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 2015-06-11
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 2017-10-03
    • 2021-04-16
    相关资源
    最近更新 更多