簡體   English   中英

Node.js、Mongoose:無法讀取 null 的屬性(讀取“比較密碼”)

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

我試圖在我的 userController.js 中更新UserPassword 並遇到以下錯誤。 不確定這可能是什么錯誤。 任何輸入和知識將不勝感激。

在 postman 上出現此錯誤

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

身體

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

用戶控制器.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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM