nodejs,编辑个人资料,密码。 Mongoose和MongoDB

时间:2018-05-20 12:07:15

标签: node.js mongodb mongoose

问题是当req.body.password为空时它不会改变毕业的值。虽然req.body.password为空,但毕业也应该改变。但是当req.body.password和同时应该更新的毕业值时,密码不应该改变。因此,当用户未更改密码并将其保留为空白时,不会更改“毕业”的值。有什么建议吗?

router.post('/edit', isAuthenticated, function (req, res, next) {
    User.findOneAndUpdate({_id: req.user._id}, {$set:{

        email: req.body.email,
        name: req.body.name,
        phone: req.body.phone,
        classc: req.body.classc,
        major: req.body.major,
        minor: req.body.mino,
        linkedin: req.body.linkedin,
        bio: req.body.bio
}
 },{ new: true }, function (err, user, done){

        if (err) {
          return err;
        } 

        else {

            if (typeof req.body.graduated == 'undefined') {
               user.graduated = false;


            } else if (typeof req.body.graduated == 'string') {
                user.graduated = true;

            }

          if (req.body.password) {
            user.password = req.body.password;
            user.save()
          } else {

          }

        }
        res.redirect('/profile');
    });

这是我的预更新功能

userSchema.pre('save', function(next) {      
    console.log                                                                                                                                  
    if(this.password){                                                                                                                                                                                                                                                                                      
        this.password  = bcrypt.hashSync(this.password, bcrypt.genSaltSync(8),null);                                                                                                             
    }



    next()                                                                                                                                                                     
}); 

1 个答案:

答案 0 :(得分:0)

要使值password和gradated彼此独立保存,请在两次检查后使用user.save()命令,而不是其中一个。

if (err) {
    return err;
} 

else {
    if (typeof req.body.graduated == 'undefined') {
       user.graduated = false;
    } else if (typeof req.body.graduated == 'string') {
        user.graduated = true;
    }

    if (req.body.password && req.body.password !== "") {
        user.password = req.body.password;
    } else {

    }

    user.save()
}
res.redirect('/profile');