0

I am currently doing this to register users:

const register = async (req, res) => {
  const seller = await Seller.create({ ...req.body });
  res.status(StatusCodes.CREATED).json({ seller });
};

I am using the pre-save function to hash the passwords:

 SellerSchema.pre('save', async function () {
  const salt = await bcrypt.genSalt(10);
  this.password = await bcrypt.hash(this.password, salt);
});

But when making the password change function which I have made like this:

 const updatePassword = async (req, res) => {
      const { id } = req.params;
    
      const { oldPassword, newPassword } = req.body;
    
      const seller = await Seller.findOne({ _id: id });

      if(!seller) throw new NotFoundError(`No seller with id:${id} exists`)
    
      const isPasswordCorrect = await seller.comparePassword(oldPassword);
      if (!isPasswordCorrect) {
        throw new UnauthenticatedError('Invalid Credentials');
      }
      seller.update({ password: newPassword });
    
      await seller.save();
    
      res.status(StatusCodes.OK).json({ seller });
    };

But what happens is the pre-save function hashes the existing password before saving; how do I make it hash the incoming password? I know I can remove the pre-save function and just use it in the controller. But is there any way to do this by using the pre-save function?

Vromahya
  • 51
  • 6
  • i am not still clear on what is your issue. but as i assume you are getting error of Invalid Credentials for valid old password. If that is the case can you tell me what exactly you are doing in your comparePassword method? – Brijesh Dave Aug 04 '22 at 10:20

1 Answers1

0
  const updatePassword = async (req, res) => {
  const { id } = req.params;

  const { oldPassword, newPassword } = req.body;

  const seller = await Seller.findOne({ _id: id });

  if(!seller) throw new NotFoundError(`No seller with id:${id} exists`)

  const isPasswordCorrect = await seller.comparePassword(oldPassword);
  if (!isPasswordCorrect) {
    throw new UnauthenticatedError('Invalid Credentials');
  }
  // Correct this line of code 
  seller.password=newPassword

  await seller.save();

  res.status(StatusCodes.OK).json({ seller });
};