Home > Software engineering >  How to update Bcrypt password with pre("findOneAndUpdate")
How to update Bcrypt password with pre("findOneAndUpdate")

Time:05-02

I want to update my hashed password which is stored in the mongodb database. I tried using pre-findOneAndUpdate but is not being triggered. In place of the response I am getting the same hashed password which is in my database.

Below is my code for pre hooks

userSchema.pre("findOneAndUpdate", async function (next) {
  if (this.password) {
    const passwordHash = await bcrypt.hash(this.password, 10);
    this.password = passwordHash;
    this.confirmpw = undefined;
  }
  next();
});

userSchema.pre("save", async function (next) {
  if (this.isModified("password")) {
    const passwordHash = await bcrypt.hash(this.password, 10);
    this.password = passwordHash;
    this.confirmpw = undefined;
  }
  next();
});

Below is my post request code from my route

router.post("/:id", async (req, res) => {
  const password = req.body.chpassword;

  await userModel
    .findOneAndUpdate({ username: req.params.id }, { password: password })
    .then((userdetails) => {
      res.status(200).json({
        password: userdetails.password,
      });
    })
    .catch((err) => {
      console.log(err);

      res.status(404).send(err);
    });
});

CodePudding user response:

Try this:

userSchema.pre("findOneAndUpdate", async function (next) {
  const update = this.getUpdate() // {password: "..."}
  if (update.password) {
    const passwordHash = await bcrypt.hash(update.password, 10);
    this.setUpdate({ $set: { 
       password: passwordHash, 
       confirmpw: undefined 
      } 
    });
  }
  next()
});
  • Related