猫鼬-如何在预(保存/更新)中间件中抛出多个错误?

时间:2020-01-03 14:08:59

标签: javascript node.js mongodb mongoose hook

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

文档中包含有关 next 函数的信息:

多次调用next()是禁止操作。如果您以错误err1调用next()然后抛出错误err2,猫鼬将报告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'))
})

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

2 个答案:

答案 0 :(得分:1)

您可以将错误添加到数组中,然后如果数组的长度大于0,则可以通过加入错误来发送一条错误消息。

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

答案 1 :(得分:0)

您好,丹尼尔欢迎您参加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))
})