Sling Academy
Home/Node.js/Mongoose: Exclude fields from query results (with examples)

Mongoose: Exclude fields from query results (with examples)

Last updated: December 30, 2023

Mongoose is a robust tool for managing data in MongoDB. One of its powerful features is the ability to tailor query results, including excluding specific fields. This tutorial demonstrates various methods to exclude fields from Mongoose query results, improving query efficiency and security.

Basic Examples

Selecting Fields

To manipulate the result set in Mongoose, the .select() method is typically used. By prefixing a field name with a minus sign, you can exclude it from the results. Here’s a simple example:

const result = await Model.find().select('-sensitiveField');

Using Query Objects

Alternatively, you can use a query object with zero for the fields you wish to exclude:

const result = await Model.find({}, { sensitiveField: 0 });

Excluding Fields in Subdocuments

For subdocuments, you can exclude fields by specifying the path:

const result = await Model.find().select('-subdocument.sensitiveField');

Global Schema Configuration

You can set default behaviors at the schema level to exclude fields:

const schema = new Schema({ /* schema fields */ }, { toJSON: { transform: (doc, ret) => { delete ret.sensitiveField; } } });

Advanced Examples

Excluding Fields on Update Operations

Excluding fields can also be achieved when performing update operations, which ensures sensitive or irrelevant fields are not unintentionally modified:

const result = await Model.findByIdAndUpdate(id, update, { fields: { sensitiveField: 0 } });

Chaining Select Queries

For more intricate queries, .select() can also be chained, which is useful when conditional logic is needed:

const query = Model.find();
if (condition) {
  query.select('-fieldA');
}
if (anotherCondition) {
  query.select('-fieldB');
}
const result = await query.exec();

Projection Operators for Complex Exclusions

When dealing with arrays or more complex structures within your documents, projection operators such as $elemMatch and $slice can be useful in crafting precise query results:

const result = await Model.find({}, { arrayField: { $elemMatch: { fieldToExclude: 0 } } });

Using Aggregation Pipelines for Exclusion

Aggregation pipelines provide granular control over the data transformation and can also be used to exclude fields:

const result = await Model.aggregate([
  { $project: { sensitiveField: 0 } }
]);

Conclusion

This tutorial has presented various ways to exclude fields from Mongoose queries, ranging from basic to advanced techniques. Using these methods selectively exposes only necessary data, optimizing network bandwidth and bolstering application security.

Next Article: How to Cascade Delete in Mongoose (with examples)

Previous Article: Mongoose $lookup operator (with examples)

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates