Sling Academy
Home/Node.js/Understanding the Mongoose exec() Function: Guide With Examples

Understanding the Mongoose exec() Function: Guide With Examples

Last updated: December 30, 2023

The exec() function in Mongoose isn’t a feature added on a specific date to the language; rather, it’s a method provided by Mongoose, an Object Data Modeling (ODM) library for MongoDB and Node.js, that has been part of the library for many versions. It is used for executing a query that has been built up using the Mongoose chainable query builder.

The primary purpose of the exec() function is to execute a built query and return a promise, allowing better handling of both asynchronous operations and potential errors using promise chains or async/await syntax.

Syntax and Parameters

Query.prototype.exec([operation], [callback])

The exec() function optionally takes an operation argument and a callback. If no callback is provided, it returns a promise.

exec() returns a promise that resolves with the result of the query if no callback is provided.

Code Examples

1. Basic Query Execution

Summary: This example demonstrates executing a simple query to find all documents within a collection.

const mongoose = require('mongoose');
const { Schema } = mongoose;

const userSchema = new Schema({ name: String, age: Number });
const User = mongoose.model('User', userSchema);

mongoose.connect('mongodb://localhost:27017/databaseName');

const query = User.find({ age: { $gte: 18 } });
query.exec().then(users => {
  console.log(users);
}).catch(err => {
  throw err;
});

2. Using Async/Await

Summary: This example shows how to use the async/await syntax along with exec() to handle query execution.

const mongoose = require('mongoose');
const { Schema } = mongoose;

// ... (setup User model as previously shown) ...

mongoose.connect('mongodb://localhost:27017/databaseName');

async function findAdults() {
  try {
    const adults = await User.find({ age: { $gte: 18 } }).exec();
    console.log(adults);
  } catch(err) {
    console.error(err);
  }
}

findAdults();

Conclusion

In this guide, you have learned about the exec() function provided by Mongoose for Node.js. It supports the modern asynchronous nature of JavaScript by returning a promise when it is not given a callback function. By understanding how to use exec(), one can more effectively write queries that are both easy to read and robust in handling asynchronous database interactions within a Node.js and MongoDB environment.

Next Article: How to Perform Bulk Upsert in Mongoose

Previous Article: How to Cascade Delete in Mongoose (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