Don’t use  “findOneAndUpdate” mongoose methods for updating password

Don’t use “findOneAndUpdate” mongoose methods for updating password

Hello GUYS!

Here is how we gonna write the "update password " controller together

1. Grab an old and new password from the body
2. Now we have to check if we pass both the old and new passwords to req. body
3. Great, we have to find a logged-in user,
when a user logged in, we set a user id to req. user,
so we can access it anywhere inside our controller

Now we have to check if the old password is matching with the password in the database

So, we have to avoid using the findOneandUpdate mongoose method while we try to update the password

we have to use pre-middleware called save

const updatePassword = async (req, res) => { 
    const { oldPassword, newPassword } = req.body;

    if (!oldPassword || !newPassword) {
        throw new BadRequestError("Please Provide both values");
    }

    const user = await userModel.findOne({ _id: req.user.userId });
    if (!(await user.comparePassword(oldPassword))) { 
        throw new UnauthenticatedError("Invalid Credentilas");
    }

    // XX Please don't do this way
    // it directly update password without hashing password 
    const updated = await userModel.findOneAndUpdate(
        { _id: req.user.userId },
        { password: newPassword }, 
        { new: true }
    );

    // Please do this way
    user.password = newPassword; 
    const updatedPassword = await user.save();
    res.status(201).json({ msg: "Success! });
};

If you find it useful don't forget to Like and Follow for more.