我正在使用express-validator,并且使用mongoose数据库find进行了一个自定义验证,现在我无法发送withMessage。这是我的代码,尽管进程在Error处停止,但是在Json中不显示消息,但是在用户创建时显示全部。
body('mobile', 'Mobile number is required')
.custom((value, {req, loc, path}) => {
User.countDocuments({mobile: value}, function (err, c) {
if (err) {
console.log('An error happen in db')
}
if (c > 0) {
throw new Error('Mobile already exists finally')
} else {
return value
}
})
return value
})
.withMessage('Mobile already exists'),
以下是控制台的日志
functions: Beginning execution of "app"
> events.js:298
> throw er; // Unhandled 'error' event
> ^
>
> Error: Mobile already exists finally
> at /Users/kamal/Documents/personal/asghar/codes/functions/app/controllers/users_controller.js:117:23
> at /Users/kamal/Documents/personal/asghar/codes/functions/node_modules/mongoose/lib/model.js:4849:16
> at /Users/kamal/Documents/personal/asghar/codes/functions/node_modules/mongoose/lib/model.js:4849:16
> at /Users/kamal/Documents/personal/asghar/codes/functions/node_modules/mongoose/lib/helpers/promiseOrCallback.js:24:16
> at /Users/kamal/Documents/personal/asghar/codes/functions/node_modules/mongoose/lib/model.js:4872:21
> at /Users/kamal/Documents/personal/asghar/codes/functions/node_modules/mongoose/lib/query.js:4379:11
> at /Users/kamal/Documents/personal/asghar/codes/functions/node_modules/kareem/index.js:135:16
> at processTicksAndRejections (internal/process/task_queues.js:79:11)
> Emitted 'error' event on Function instance at:
> at /Users/kamal/Documents/personal/asghar/codes/functions/node_modules/mongoose/lib/model.js:4851:13
> at /Users/kamal/Documents/personal/asghar/codes/functions/node_modules/mongoose/lib/helpers/promiseOrCallback.js:24:16
> [... lines matching original stack trace ...]
我需要添加,如果条件接近return value
,但问题是在这里回调并没有带给我c的值,在上面它是正确的,甚至由于错误引发而停止,但是我不想引发错误想进一步withMessage('Mobile already exists')
我肯定在回调中做错了。请提出解决方法
这应该工作
body("mobile").custom(value => {
return User.countDocuments({ mobile: value })
.then(count => {
if (count > 0) return Promise.reject("Mobile Number already Exists");
})
.catch(error => console.error(error.message));
});