DEV Community

Simran
Simran

Posted on

7 1

Removing specific fields from a Mongoose returned object

Original Post Link...

Very often we have the need to only read certain fields from the database. We might just need username from a collection that has a bunch of other fields related to a User as well or read all the fields except 1 or 2, like we would never want to return password to the client when we are sending the User object even when it is ecrypted. For such scenerios Mongoose gives few different ways to include or exclude fields from the response we read from a MongoDB collection.

Including a certain field

If we want to include only 1 single field from a collection in the response we can use .include("<field-name>") after the mongoose query.

await User.find({}).select("username");
Enter fullscreen mode Exit fullscreen mode

The above example will only return username and _id from the User collection.

Excluding a certain field

If we want to exclude only 1 single field from a collection in the response we can use .include("-<field-name>") after the mongoose query.

await User.find({}).select("-username");
Enter fullscreen mode Exit fullscreen mode

The above example will exclude username from the User collection and return all other fields.

Always remove a certain field when Mongoose Schema returns a response

There are situations when we never want to return a field in the results from the Mongoose query. In such situations Mongoose itself provides us a way to modify its JSON object at the schema level and we can modify it the way we want.

userSchema.methods.toJSON = function () {
    const user = this;
    const userObject = user.toObject();

    delete userObject.password;

    return userObject;
}
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay