ignore certain fields from mongoose schema when return object to client

override the toJSON

This will remove the password part in the target object.

UserSchema.methods.toJSON = function() {
  var obj = this.toObject()
  delete obj.passwordHash
  return obj
}

documented way

The mongoose document is in the toOject() part

toJson

  • doc The mongoose document which is being converted
  • ret The plain object representation which has been converted
  • options The options in use (either schema options or the options passed inline)
UserSchema.set('toJSON', {
    transform: function(doc, ret, options) {
        delete ret.password;
        return ret;
    }
});

use a white list

UserSchema.set('toJSON', {
    transform: function(doc, ret, options) {
        var retJson = {
            email: ret.email,
            registered: ret.registered,
            modified: ret.modified
        };
        return retJson;
    }
});
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s