Alfonso Embid-Desmet
Alfonso Embid-Desmet

Reputation: 3622

Censoring MongoDB fields with Mongoose

I am thinking on the best way to censor some MongoDB fields using Mongoose ORM. Having

const userSchema = new Schema({
  last_name: {
  type: String,
  select: false,
  }
});

userSchema.virtual('last_name_initial').get(function () {
  return this.last_name.substr(0,1).toUpperCase();
});

Wouldn't do it because last_name is set as select: false, Obviously I don't want to send back last_name

Upvotes: 0

Views: 161

Answers (1)

ZeMoon
ZeMoon

Reputation: 20274

When you specify {select: false} on any field in the schema, the field is excluded in queries by default. So, in this case, your virtual field will only work objects which have been queried like this:

User.find().select('+last_name').exec(function (err, users) {

    //The virtual field should be available here.
    console.log(users[0].last_name_initial);
});

If you want the virtual field to always be available without having to explicitly include the field for selection then it would be better to use another approach than {select: false}.

One way you could exclude the field by default is by overriding the toJSON method (source had the same problem as you)

userSchema.methods.toJSON = function() {
  var obj = this.toObject()
  delete obj.last_name
  return obj
}

NOTE: With this approach, you should also set the option {virtuals: true} for toJSON.

userSchema.set('toJSON', {virtuals: true});

Upvotes: 2

Related Questions