[英]Mongoose - How can I throw more than one error in pre (save/update) middleware?
我在模型中有一些預保存和更新掛鈎,我需要同時顯示所有驗證錯誤。
文檔中有關於下一個函數的信息:
多次調用 next() 是無操作的。 如果調用 next() 時報錯 err1,然后拋出錯誤 err2,mongoose 將報告 err1。
請參閱此處的參考
我想做一些類似下面的代碼來返回兩個或更多驗證錯誤,但像文檔一樣只拋出第一個錯誤
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,您可以使用它的驗證功能。
其他一些驗證包是:
你好 Daniel 歡迎來到 Stack Overflow!
我的方法是將錯誤保存到可迭代對象中,然后將可迭代對象作為錯誤對象發送join()
如果只接受字符串,則使用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))
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.