yiooxir yiooxir -4 years ago 301
Node.js Question

Mongoose virtual field not updated

i created a schema for user like this:

var schema = new Schema({
username: {
type: String,
unique: true,
required: true
},
hashedPassword: {
type: String,
required: true
},
salt: {
type: String,
required: true
}
});

schema.virtual('password')
.set(function(password) {
this._plainPassword = password;
this.salt = Math.random() + '';
this.hashedPassword = this.encryptPassword(password);
})
.get(function() { return this._plainPassword; });

schema.methods.encryptPassword = function(password) {
return crypto.createHmac('sha1', this.salt).update(password).digest('hex');
};


then I'm trying to change the password using the two approaches:


  1. work nice

    User.findById('userId..', function(err, user) {
    user.password = '456';
    user.save(cb);
    })

  2. why is this approach not working ?

    User.findByIdAndUpdate('userId', {$set: {password: '456'}}, cb)


Answer Source

This happens because Mongoose doesn't apply any of the following on a findByIdAndUpdate() operation:

  • defaults
  • setters
  • validators
  • middleware

From the docs:

If you need those features, use the traditional approach of first retrieving the document.

Model.findById(id, function (err, doc) {
  if (err) ..
  doc.name = 'jason borne';
  doc.save(callback);
})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download