Node.js、Mongoose:无法读取 null 的属性(读取 'comparePassword')

Node.js, Mongoose: Cannot read properties of null (reading 'comparePassword')

我试图在 userController.js 中更新用户密码,但遇到了以下错误。不确定这可能是哪种错误。任何意见和知识将不胜感激。

邮递员收到此错误

{
    "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

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

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