Hide properties of Mongoose objects in Node.JS JSON responses

Originally published here: https://blog.contactsunny.com/hide-properties-of-mongoose-objects-in-node-js-json-responses/

Image for post
Image for post

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’);

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.

Coding, machine learning, reading, sleeping, listening, potato. https://blog.contactsunny.com and https://www.linkedin.com/in/sunnysrinidhi/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store