【问题标题】:Node.js, Mongoose: Cannot read properties of null (reading 'comparePassword')Node.js,Mongoose:无法读取 null 的属性(读取“comparePassword”)
【发布时间】:2022-01-09 17:54:26
【问题描述】:

我试图在我的 userController.js 中更新UserPassword 并遇到以下错误。不确定这可能是什么错误。任何意见和知识将不胜感激。

在邮递员上收到此错误

{
    "msg": "Cannot read properties of null (reading 'comparePassword')"
}

身体

{
    "oldPassword":"secret",
    "newPassword":"newsecret"
}

userController.js

const updateUserPassword = async (req, res) => {
  const { oldPassword, newPassword } = req.body;
  if (!oldPassword || !newPassword) {
    throw new CustomError.BadRequestError('Please provide both values');
  }
  const user = await User.findOne({ _id: req.user.userId });

  const isPasswordValid = await user.comparePassword(oldPassword);
  if (!isPasswordValid) {
    throw new CustomError.UnauthenticatedError('Invalid Credentials');
  }
  user.password = newPassword;

  await user.save();
  res.status(StatusCodes.OK).json({ msg: 'Success! Password Updated.' });
};

Github:https://github.com/k4u5hik/node-express-course

【问题讨论】:

    标签: node.js mongoose postman


    【解决方案1】:

    调用user.camparePassword前需要检查用户是否存在,例如:

    const user = await User.findOne({ _id: req.user.userId });
    if (!user) {
      throw new CustomError.UserNotFound();
    }
    const isPasswordValid = await user.comparePassword(oldPassword);
    
    

    【讨论】:

    • 目前没有删除用户的功能。更新密码的用户必须登录。因此可以安全地假设他们会在这种情况下存在。
    • PS:我确实尝试添加该代码,但错误仍然存​​在。
    • 你好,duy le,我确实添加了代码,问题今天解决了,虽然昨天没有。谢谢!
    • 我很高兴听到这个消息。如果对您解决问题有帮助,请选择我的答案作为已接受的答案。
    猜你喜欢
    • 2012-10-03
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2020-07-31
    • 2021-11-28
    • 2022-01-12
    相关资源
    最近更新 更多