Facebook Pixel
Step-by-Step Guide

How to Build a REST API with Express and MongoDB

A step-by-step guide on how to build a complete CRUD REST API using Express.js and MongoDB with Mongoose for data modeling.

Set Up the Project Structure

Create a new directory and initialize it with npm init. Install express, mongoose, and dotenv. Organize your project into folders: routes for URL definitions, controllers for request handling logic, models for database schemas, and middleware for reusable request processing functions. This separation of concerns keeps the codebase maintainable as it grows.

Connect to MongoDB with Mongoose

Import mongoose and call mongoose.connect with your MongoDB connection string inside an async function. Wrap it in a try-catch and log errors clearly. Call this function when your server starts. Mongoose manages a connection pool internally, so you connect once at startup and Mongoose reuses that connection for all subsequent database operations.

Define a Mongoose Schema and Model

A schema defines the shape and validation rules of documents in a collection. Create a schema using new mongoose.Schema and define each field with its type and optional constraints like required, unique, minlength, and default values. Call mongoose.model with a name and the schema to create a model, which is the class you use to interact with the collection.

Implement the Create Endpoint

In your controller, handle POST requests by extracting data from req.body. Create a new model instance and call the save method on it. Await the result. If validation passes and the document saves successfully, send a 201 status with the created document. If a validation error occurs, it will be caught by your error handler and returned with a 400 status.

Implement the Read Endpoints

For fetching all documents, call Model.find with an optional filter object and await the result. For fetching a single document, call Model.findById with the ID from req.params and await the result. If findById returns null, the document does not exist and you should send a 404 response. Always handle this case explicitly.

Implement the Update Endpoint

Handle PATCH requests by calling Model.findByIdAndUpdate with the document ID, the update object from req.body, and an options object containing new: true and runValidators: true. The new option returns the updated document instead of the original. The runValidators option ensures Mongoose schema validations are applied to the updated fields.

Implement the Delete Endpoint

Handle DELETE requests by calling Model.findByIdAndDelete with the document ID from req.params. If the result is null, the document did not exist and you should return a 404. If successful, return a 204 No Content status with no body, which is the REST convention for a successful deletion that returns nothing.

Add Pagination to List Endpoints

Returning all documents from a large collection in one response is slow and expensive. Accept page and limit query parameters from the request. Use Mongoose's skip method with the value of page minus one multiplied by limit, and chain the limit method with the limit value. Also query the total count using Model.countDocuments and include it in the response so clients know how many pages exist.

Ready to master this completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.