Javascript 如何制作猫鼬';s model.findByIdAndUpdate()触发model.save()?

Javascript 如何制作猫鼬';s model.findByIdAndUpdate()触发model.save()?,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我的数据库中有一个mongoose模型供用户使用。我有一个更新控制器,它在我的模型上调用findByIdAndUpdate方法。现在,当我在数据库中存储密码时,我想先对它们进行散列,因此我有: userSchema.pre("save", async function(next) { // if password is modified then hash it next(); }); 现在,当我的更新控制器调用findbyidanddupdate时,在我看来,model.save()

我的数据库中有一个mongoose模型供用户使用。我有一个更新控制器,它在我的模型上调用
findByIdAndUpdate
方法。现在,当我在数据库中存储密码时,我想先对它们进行散列,因此我有:

userSchema.pre("save", async function(next) {
  // if password is modified then hash it
  next();
});
现在,当我的更新控制器调用
findbyidanddupdate
时,在我看来,
model.save()
没有被调用,因此哈希从未发生

有没有办法重载
findByAndUpdate
的原始行为,或者这个问题的简单解决方案是什么?

触发中间件。未在findOneAndUpdate()上执行Pre和post save()挂钩

您无法访问
pre('findOneAndUpdate')
中间件中正在更新的文档。 如果需要访问将要更新的文档,则需要对该文档执行显式查询

findOneAndUpdate中间件的示例架构:

const mongoose=require(“mongoose”);
const bcrypt=require(“bcryptjs”);
const schema=new mongoose.schema({
用户名:{
类型:字符串,
要求:正确,
独一无二:真的
},
电邮:{
类型:字符串,
要求:正确,
独一无二:真的
},
密码:{
类型:字符串,
必填项:true
}
});
schema.pre(“保存”,异步函数(下一步){
如果(!this.isModified(“password”))返回next();
this.password=wait bcrypt.hash(this.password,12);
next();
});
schema.pre(“findOneAndUpdate”,异步函数(){
const docToUpdate=等待this.model.findOne(this.getQuery());
//将哈希逻辑添加到此处
让newPassword=wait bcrypt.hash(docToUpdate.password,12);
this.set({password:newPassword});
});
module.exports=mongoose.model(“用户”,模式);
测试的样本路径:

router.put(“/users/:id”),异步(req,res)=>{
让result=wait User.findByIdAndUpdate(req.params.id,{},{new:true});
res.send(结果);
});
请注意,我在findbyiandupdate中使用了{},因为我们的密码将在
findOneAndUpdate
中间件中散列