【发布时间】:2020-04-24 15:05:06
【问题描述】:
我正在使用 express-validator 并使用 mongoose 数据库查找进行了一项自定义验证,现在我无法发送 withMessage。这是我的代码,虽然进程在错误处停止,但它没有在 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 附近添加 if 条件,但问题是回调不会在这里给我带来 c 的值,在上面它是正确的,甚至由于错误引发而停止,但我不想引发错误相反,我想更进一步withMessage('Mobile already exists')我肯定在回调中做错了。请提出解决方案
【问题讨论】:
-
您可以将输出发布到控制台吗? (如果有的话)
-
您必须在条件为
(c>0)的 if 块下发送您的消息,否则根据您的设置它会抛出错误并退出。 -
已经把控制台我做了,但它没有效果 withMessage 的正文消息创建整个数组,而不是由 Json 返回的返回。