javascript - Mongoose - 如何在预(保存/更新)中间件中引发多个错误?

标签 javascript node.js mongodb mongoose hook

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

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

Calling next() multiple times is a no-op. If you call next() with an error err1 and then throw an error err2, mongoose will report 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'))
})

我该怎么做?有替代方案吗?

最佳答案

你可以将你的错误添加到一个数组中,然后如果数组的长度大于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();
});

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

其他一些验证包是:

  1. Express Validator
  2. Joi

关于javascript - Mongoose - 如何在预(保存/更新)中间件中引发多个错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59579988/

相关文章:

javascript - 如何序列化NodeJS?

MongoDB:如何在不指定数组索引的情况下查找任何字段的子文档中包含字符串的文档?

javascript - jQuery/js 删除动态创建的复选框

javascript - 使用 Firebase Cloud Functions 访问 Firebase Storage 中的文件时出现问题,文件返回 "[object Object] "

java - 如何通过 XMLHttpRequest 保护对 Java Servlet 的 Javascript 调用,以便在手动将 url 输入到浏览器中时无法使用该调用?

javascript - 在保留旧静态页面的同时拥有动态内容

c++ Interlocked Ops 在 WinXP 上

node.js - MongoDb - 要创建新的 ObjectId,请尝试 `Mongoose.Types.ObjectId` 而不是使用 `Mongoose.Schema.ObjectId`

mongodb - 迭代游标时修改Mongo对象的安全+有效方法?

linux - 如何在云 linux 上安装 mongodb