BackendNode.jsExpressMongoDBCRUDMERN Stack

CRUD API with Node.js, Express, and MongoDB in 30 Minutes

Build a complete CRUD REST API with Node.js, Express, and MongoDB from zero to deployed in 30 minutes — beginner-friendly with best practices.

Abdur Razzak

Abdur Razzak

Full-Stack Web Developer

June 19, 2025 8 min read

Setting Up the Project

Start with npm init -y and install express, mongoose, dotenv, and cors. Create a .env file with your MONGODB_URI and PORT. Create server.js with Express app setup, CORS middleware, and a mongoose.connect() call. Run with nodemon for auto-restart on file changes. This minimal setup is the foundation for every MERN stack backend project.

Creating the Mongoose Model

Define a Mongoose schema for your resource — for example, a Post with title (required String), content (required String), author (String), and timestamps (automatically added by { timestamps: true }). Export the model: module.exports = mongoose.model('Post', PostSchema). Models provide type validation, and timestamps automatically track createdAt and updatedAt.

Building the Controller

Create a controller file with async functions for each CRUD operation: getAllPosts (find all), getPostById (findById), createPost (create), updatePost (findByIdAndUpdate with { new: true }), and deletePost (findByIdAndDelete). Wrap each in try/catch and return appropriate HTTP status codes. The { new: true } option in updatePost returns the updated document, not the original.

Setting Up Routes

Create a router file with Express.Router(). Map each HTTP method to its controller: router.get('/', getAllPosts), router.get('/:id', getPostById), router.post('/', createPost), router.put('/:id', updatePost), router.delete('/:id', deletePost). Mount the router in server.js: app.use('/api/posts', postRouter). This clean separation keeps your server.js minimal and routes organized.

Input Validation

Add basic input validation in your controller before saving to the database. Use Mongoose's built-in validation (required, minlength, maxlength) for simple rules. For more complex validation, use Zod or Joi to validate the request body before passing it to Mongoose. Return a 400 status with descriptive error messages when validation fails — never let invalid data reach the database layer.

Testing and Deploying

Test your endpoints with Postman or Thunder Client (VS Code extension). Test all CRUD operations, including error cases (invalid ID, missing required fields). Deploy to Railway, Render, or Heroku by connecting your GitHub repository and adding environment variables in the platform dashboard. Railway.app is my recommended hosting for MERN stack backends — it is free to start and deploys in minutes.

Share this article

All posts
#Node.js#Express#MongoDB#CRUD#MERN Stack
Abdur Razzak — Full Stack Web Developer

Free Consultation

Got a Project Idea? Let's Talk.