Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update one field in mongoose model (node.js)

I have a user schema where I want to update some info, like this.

User.findOne({_id: idd}, function(err, usr){
   usr.info = "some new info";
   usr.save(function(err) {
   });
});

But the model has a hook on save to hash the password

UserSchema.pre('save', function(next) {
    if (this.password && this.password.length > 6) {
        this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
        this.password = this.hashPassword(this.password);
    }

    next();
});

Now when I try to save it takes the allready hased password and hash it again, any idea how to avoid this?

like image 691
user1930848 Avatar asked Nov 26 '14 19:11

user1930848


1 Answers

Use Model.Update and move the creation of a new password to an independent function.

var salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');;
var newPassword = this.hashPassword("someNew password");
User.update({_id: idd}, {
    info: "some new info", 
    password: newPassword
}, function(err, affected, resp) {
   console.log(resp);
})
like image 110
BatScream Avatar answered Oct 01 '22 13:10

BatScream