Nam Nguyen
Nam Nguyen

Reputation: 5750

Mongoose Setters only get called when create a new doc?

I use Mongoose getter and setter I recently found that setter only applies when I create a new doc (UserSchema.create...) but setter will not get called for update (UserSchema.findByIdAndUpdate...). Am I right or am I missing anything. If I'm right, is there setter for update?

(http://mongoosejs.com/docs/2.7.x/docs/getters-setters.html

Thanks.

UPDATED

I found git issue: https://github.com/LearnBoost/mongoose/issues/751 , it means this is expected behavior. Not sure I'm right.

Upvotes: 1

Views: 1514

Answers (2)

prototype
prototype

Reputation: 7970

Found a nice method that encapsulates that from https://groups.google.com/forum/?fromgroups=#!topic/mongoose-orm/8AV6aoJzdiQ:

function findByIdAndSave( model, id, data, next ){

  model.findById( id, function( err, doc ) {
    if( err ){
      next( err, null );
    } else {
      if(! doc ){
        next( new Error("Object to save not found"), null );
      } else {
        // There must be a better way of doing this
        for( var k in data ){
          doc[k] = data[k];
        }
        doc.save( next );
      }
    }
  });
}

(This really belongs as a comment, but the answer allows better code formatting)

Upvotes: 0

Nam Nguyen
Nam Nguyen

Reputation: 5750

Found out that I should not use findByIdAndUpdate, instead I should query object, edit and save.

Upvotes: 1

Related Questions