你好我的预先保存它的工作,当我注册,但预先更新它不工作当我在editprofile中更改我的个人资料..谁都知道如何解决这个问题..
userSchema.pre('update', function(next) {
this.update({},{ $set: {password: bcrypt.hashSync(password, bcrypt.genSaltSync(8),null) } });
next()
});
userSchema.pre('save', function(next) {
if(this.password) {
this.password = bcrypt.hashSync(this.password, bcrypt.genSaltSync(8),null);
}
next()
});
答案 0 :(得分:1)
您可以使用findOneAndUpdate
,然后再次运行.save()
来设置密码bcrypted
router.post('/edit', isAuthenticated, function (req, res, next) {
User.findOneAndUpdate({_id: req.user._id}, {$set: req.body},{ new: true }, function (err, user){
if (err) {
return err;
} else {
if (req.body.password) {
user.password = req.body.password;
user.save();
} else {
// if body does not contain password
}
}
})
})