【问题标题】:Why isn't my mongoose validation method on the model not working with Joi?为什么我的模型上的猫鼬验证方法不能与 Joi 一起使用?
【发布时间】:2019-06-16 09:53:12
【问题描述】:

问题

我设置了一个基本的身份验证流程。 我的用户模型上有这个自定义方法:

userSchema.methods.joiValidate = function() {
  console.log(typeof this.username);
  const Joi = require("joi");
  const schema = {
    username: Joi.types.String.min(6)
      .max(24)
      .required(),
    email: Joi.types.String.email().required(),
    password: Joi.types.String.min(8)
      .max(30)
      .regex(/[a-zA-Z0-9]{3,30}/)
      .required()
  };
  return Joi.validate(this, schema);
};

但它没有按预期工作。

当我创建一个新用户并像这样验证它时:

const invalidUser = new User({
      username: "bob",
      email: "test@gmail.com",
      password: "test123"
    });
invalidUser.joiValidate();

我收到此错误消息:TypeError: Cannot read property 'String' of undefined

我不知道为什么? this 在我的方法中指的是确切的这个用户,当我将它控制台登录到模型(文档)本身时,它上面有所有必填字段(用户名、电子邮件和密码)。 我也尝试在方法上Joi.validate(this.toObject(), schema),但这并没有改变任何东西。

谁能解释一下发生了什么以及为什么它不起作用?

【问题讨论】:

    标签: node.js mongoose joi


    【解决方案1】:

    对于任何好奇问题出在哪里的人 - 我以某种方式弄乱了 joi 的整个语法(复制了我在 StackOverflow 上找到的一些旧代码,哈哈)。

    我是这样解决的:

        userSchema.methods.joiValidate = function() {
        
          // pull out just the properties that has to be checked (generated fields from mongoose we ignore)
          const { username, email, password } = this;
          const user = { username, email, password };
          const Joi = require("joi");
          const schema = Joi.object().keys({
            username: Joi.string()
              .min(6)
              .max(24)
              .required(),
            email: Joi.string()
              .email()
              .required(),
            password: Joi.string()
              .min(8)
              .max(30)
              .regex(/[a-zA-Z0-9]{3,30}/)
              .required(),
            _id: Joi.string()
          });
        
          return Joi.validate(user, schema, { abortEarly: false });
        };
    

    【讨论】:

      猜你喜欢
      • 2017-07-07
      • 1970-01-01
      • 2020-07-03
      • 2017-01-04
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      • 2011-06-05
      • 1970-01-01
      相关资源
      最近更新 更多