我試圖在我的 userController.js 中更新UserPassword 并遇到以下錯誤。不確定這可能是什么錯誤。任何輸入和知識將不勝感激。
在郵遞員上收到此錯誤
{
"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
uj5u.com熱心網友回復:
在呼叫 user.camparePassword 之前需要檢查用戶是否存在,例如:
const user = await User.findOne({ _id: req.user.userId });
if (!user) {
throw new CustomError.UserNotFound();
}
const isPasswordValid = await user.comparePassword(oldPassword);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/408426.html
標籤:
