![](/img/trans.png)
[英]node.js:TypeError: Cannot read properties of null (reading 'matches')
[英]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.' });
};
在調用 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.