Hide properties of Mongoose objects in Node.JS JSON responses

Sunny Srinidhi
2 min readJul 19, 2017

--

Originally published here: https://blog.contactsunny.com/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 (yet). 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?

Follow me on Twitter for more Data Science, Machine Learning, and general tech updates. Also, you can follow my personal blog as I post a lot of my tutorials, how-to posts, and machine learning goodness there before Medium.

--

--