我想更新存盤在 mongodb 資料庫中的哈希密碼。我嘗試使用 pre-findOneAndUpdate 但沒有被觸發。代替回應,我得到了與我的資料庫中相同的散列密碼。
下面是我的 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();
});
以下是我的路線中的帖子請求代碼
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);
});
});
uj5u.com熱心網友回復:
試試這個:
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()
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470266.html
上一篇:帶有條件的mongodb更新
下一篇:Mongodb用比率比較兩個欄位