Javascript 为什么不是';t mongoose自定义错误处理不起作用
我正在尝试处理所需的验证错误,以使错误消息在传递到前端之前更具可读性:Javascript 为什么不是';t mongoose自定义错误处理不起作用,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我正在尝试处理所需的验证错误,以使错误消息在传递到前端之前更具可读性: UserSchema .post('save', function (error, doc, next) { console.log(error.errors); if (error.name === 'ValidationError' && error.errors.academicRole.kind === 'required') { console.log('custom
UserSchema
.post('save', function (error, doc, next) {
console.log(error.errors);
if (error.name === 'ValidationError' && error.errors.academicRole.kind === 'required') {
console.log('custom error');
next(new Error('Academic Role is required.'));
} else {
next(error);
}
});
此代码导致在缺少academicRole属性时调用用户的save回调,错误为空对象;为什么不使用包含自定义消息的错误对象调用save回调?应该在钩子中检查验证错误 如果存在验证错误,则不会调用save()方法和关联的挂钩pre('save')和post('save')
UserSchema
.post('validate', function (err, doc, next) {
console.log(err.errors);
if (err.name === 'ValidationError' && err.errors.academicRole.kind === 'required') {
console.log('custom error');
next(new Error('Academic Role is required.'));
} else {
next(err);
}
});
使用该代码,不会记录任何内容。Mongoose的文档似乎也表明错误是在错误处理中间件下的post save中处理的。它说:“验证是异步递归的;当您调用Model#save时,也会执行子文档验证。如果发生错误,您的Model#save回调将接收它”。据我所知,这意味着该错误不会出现在
post('validate')
或post('save')
挂钩中。它实际上会显示在save()
方法本身中。请参阅。未调用post validate可能存在的问题是,我正在验证的值是未定义的
,mongoose通过设计仅使用内置的必需的
验证器进行验证,而该验证器正是我试图拦截的验证器。