Update one field in mongoose model (node.js)

I have a custom scheme where I want to update some information, for example.

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

But the model has a hook for saving to a hash 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 accepts allready hased password and hash it again, any idea how to avoid this?

+4
source share
2 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);
})
+7
source

Have you tried to use isModified?

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

    next();
});
+3
source

All Articles