我在编辑个人资料中更新密码时进行预更新

时间:2018-05-20 06:40:20

标签: node.js mongodb mongoose

你好我的预先保存它的工作,当我注册,但预先更新它不工作当我在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()                                                                                                                                                                     
}); 

1 个答案:

答案 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
          }
        }
    })
})