我在模型中有一些预保存和更新 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 .
其他一些验证包是:
关于javascript - Mongoose - 如何在预(保存/更新)中间件中引发多个错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59579988/