【问题标题】:I am getting issue in mongoose calback in custom validation我在自定义验证中遇到猫鼬回调问题
【发布时间】: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 返回的返回。

标签: node.js mongoose callback


【解决方案1】:

这应该可以工作

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));
});

来自 express-validator documentation

自定义验证器可能会返回 Promises 以指示异步验证 (将等待),或抛出任何价值/拒绝承诺 使用自定义错误消息。注意:如果您的自定义验证器返回一个 promise,它必须拒绝表明该字段无效。

【讨论】:

  • 非常抱歉延迟响应,因为它很紧急,我已经通过在模型中创建自定义方法并在验证中添加一行自己解决了这个问题,我正在分享答案,但你的答案似乎很好,但它也卡住了响应,什么也没有出现,但它一直在等待并且不得不中断请求。但我相信你已经努力回复这个问题,所以谢谢。
【解决方案2】:

在播放并查看了许多文档后,我通过以下操作解决了这个问题,在我的用户模型中我输入了以下代码,因为我的模型实际上是猫鼬模块。

UserSchema.statics = {
  isValidMobile(mobile) {
    console.log(` Searching obile ${mobile} number `)
    return this.findOne({mobile: mobile}).then((result) => {
      if (result) throw new Error('Mobile Number already exists')
    })
  },
}

现在在我的验证中,我输入了以下行而不是上面的行。

        body('mobile', 'Mobile number is required')
          .custom((val) => User.isValidMobile(val))

它起作用了,我得到了带有整个 JSON 的正确消息,因为它似乎自定义需要正确的真/假回复,所以我的方法只是回复真或假,并且它可以正常处理正确的消息,但正在使用该消息来自用户模型类而不是来自验证,但它有效。感谢您的回复。

【讨论】:

    猜你喜欢
    • 2020-03-26
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 2020-02-23
    • 2016-03-13
    • 2016-04-03
    • 2014-07-08
    相关资源
    最近更新 更多