简体   繁体   中英

mongoose password gets hashed twice

I am new to Mongoose and Node JS, and have this problem with password being hashed again after a user is updated.

Here is the code for hashing:

UserSchema.pre('save', function (next) {
    var user = this;
    bcrypt.hash(user.password, 10, function (err, hash) {
        if (err) {
            return next(err);
        }
        user.password = hash;
        next();
    })
});

and this is for updating the user

router.post('/insert', function (req, res) {
    User.findById(req.session.userId, function (err, user) {

        if (err) { throw err; }
        if (user) {
            user.patients = req.body.patients
            user.diagnosis_list = req.body.diagnosis_list
            user.medicine_dose_list = req.body.medicine_dose_list
            user.medicine_list = req.body.medicine_list

            user.save(function (err) {
                if (err) throw err;
                res.send(user.toJSON());
            })
        }
    })
})

I understand that presave has to be prevented to be called on updating the user, I just have no clue how to do that. Is there some other way I can update the user without having presave being called maybe?

if (!user.isModified('password')) {
    return next();
}
bcrypt.hash(user.password, 10, function (err, hash) {
    if (err) {
        return next(err);
    }
    user.password = hash;
    next();
})

http://mongoosejs.com/docs/api.html#document_Document-isModified

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM