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");
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");
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;
}
Top comments (0)