I was attempting to updateUserPassword in my userController.js and came across the following error. Unsure what kind of error this could be. Any input and knowledge would be appreciated.
Getting this error on postman
{
"msg": "Cannot read properties of null (reading 'comparePassword')"
}
Body
{
"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.' });
};
You need to check whether the user is exists or not before calling user.camparePassword, for example:
const user = await User.findOne({ _id: req.user.userId });
if (!user) {
throw new CustomError.UserNotFound();
}
const isPasswordValid = await user.comparePassword(oldPassword);