Node Express:Joi 未转换为小写

Node Express: Joi not converting to lowercase

在我的路由器中我有

router.post('/user/register', User.validateRegister, User.register);

并且验证寄存器函数添加了 .lowercase() 和 trim() 但是当数据到达数据库时它不是小写的?

  static validateRegister = async (req: Request, res: Response, next: NextFunction) => {
    const schema = Joi.object().keys({
      email: Joi.string().lowercase().trim().email({ minDomainSegments: 2 }),
      fullName: Joi.string().trim().max(30),
      password: Joi.string().trim().min(5),
    });
    const email = req.body.email;
    const password = req.body.password;
    const fullName = req.body.fullName;
    Joi.validate({ email, password, fullName }, schema, (err) => {
      if (!err) next(); else res.json(err.details);
    });
  };

下面是注册函数

  static register = async (req: Request, res: Response) => {
    const email = req.body.email;
    const password = req.body.password;
    const fullName = req.body.fullName;
    const alreadyRegistered = await userModel.findOne({email}).exec();
    if (!alreadyRegistered) {
      const hashedPassword = await bcrypt.hash(password, 10);
      if (!hashedPassword) {
        res.status(500).send({ message: 'Failed to encrypt your password' });
      } else {
        const user = new userModel({email, password: hashedPassword, fullName} as UserModelInterface);
        const saved = await user.save();
        if (!saved) {
          res.status(500).send({ message: 'Failed to register you' });
        } else {
          res.status(200).send({ message: 'You are now registered' });
        }
      }
    } else {
      res.status(400).send({ message: 'You have already registered' });
    }
  };

我的问题是为什么 Joi 没有将电子邮件转换为小写?

您正在使用从前端发送的数据 req.body,如果您需要经过验证的数据,那么您可以使用

Joi.validate({ email, password, fullName }, schema, (err, val) => {
  if (!err) {
    req.validatedBody = val;
    //req.body = val;
    next();
  } else {
    res.json(err.details);
  }
}); 

并且在寄存器函数中

const email = req.validatedBody.email;
const password = req.validatedBody.password;
const fullName = req.validatedBody.fullName;

即使你可以覆盖req.body(见注释行)那么你不需要改变寄存器功能