19
- July
2017
Posted By : Sunny Srinidhi
Hide properties of Mongoose objects in Node.JS JSON responses

Many a times, we’ll encounter a situation where we’ll have to hide certain properties of Mongoose objects, especially when we’re sending those objects in responses. For example, suppose you have an API endpoint like so: /user/:id. You will, obviously, send a user object as a response to this request. But there will be certain properties of the User schema (such as password) which you’d want to remove before sending the object in the response.

Laravel developers can relate this to the $hidden array in Eloquent models, which automatically hides the given list of properties before sending the object in the response.

There is no out-of-the-box solution for this in Mongoose. But it’s pretty easy to achieve, even though it’s a bit verbose. The solution is to define a custom .toJSON() method on the Mongoose schema and delete the properties which you don’t want to return in the response.

For example, let’s say you want to delete the password property from a UserSchema, you can do that by adding the following piece of code in the schema class:

 

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

The complete code for the UserSchema would look something like this:

var mongoose = require('mongoose');

var UserSchema = new mongoose.Schema({
    name: { type: String, unique: false, required: true },
    email: { type: String, unique: true, required: true },
    password: { type: String, unique: false, required: true },
    userGroup: { type: Number, unique: false, required: true, default: 2 }
});

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

module.exports = mongoose.model('User', UserSchema);

That’s not very hard to understand, is it?

Leave a Reply