如何使用 pre("findOneAndUpdate") 更新 Bcrypt 密码

How to update Bcrypt password with pre("findOneAndUpdate")

我想更新存储在 mongodb 数据库中的散列密码。我尝试使用 pre-findOneAndUpdate 但没有被触发。我得到的是数据库中相同的散列密码,而不是响应。

下面是我的预挂钩代码

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();
});

下面是我的 post 来自我的路线的请求代码

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);
    });
});

试试这个:

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()
});