Mongoose每次使用预保存钩子保存时都会更改密码

我正在使用bcrypt的预保存钩子来encryption系统上的密码。 它创build或更改密码时正常工作。 问题是,似乎每次更改并保存不同的字段(例如电子邮件)时都会重新encryption密码。

可能更容易用代码解释。 这里是模型:

const UserSchema = new Schema({ email: { type: String, required: true, lowercase: true, unique: true, trim: true }, password: { type: String, required: true } }) 

和钩子:

 UserSchema.pre('save', function(next){ const user = this; console.log(user); bcrypt.genSalt(10, function(err, salt){ if (err){ return next(err) } bcrypt.hash(user.password, salt, null, function(err, hash){ if(err){return next(err)} user.password = hash; next(); }) }) }); 

这里是我的代码来更新电子邮件地址:

 module.exports = function(req, res){ User.findOne({ _id: req.body.user}, function(err, doc){ if(err){ console.log(err); return; } doc.email = req.body.data; doc.save(function(err, returnData){ if (err){ console.log(err); return; } res.send(returnData); }) }) } 

因此,当我在最后一个例子中调用doc.save时,它会根据预期更新电子邮件地址,但是它也会重新encryption密码,这意味着如果用户退出,他们将无法再次login。

任何人都可以帮助如何解决这个问题?

尝试这个:

 UserSchema.pre('save', function(next){ if (!user.isModified('password')) return next(); const user = this; bcrypt.genSalt(10, function(err, salt){ if (err){ return next(err) } bcrypt.hash(user.password, salt, null, function(err, hash){ if(err){return next(err)} user.password = hash; next(); }) }) }); 

好的,我设法弄清楚了 – 只需要在预保存钩子中使用一点条件逻辑:

 UserSchema.pre('save', function(next){ if(!this.isModified('password')){ return next(); } // Adding this statement solved the problem!! const user = this; bcrypt.genSalt(10, function(err, salt){ if (err){ return next(err) } bcrypt.hash(user.password, salt, null, function(err, hash){ if(err){return next(err)} user.password = hash; next(); }) }) });