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
Full-Stack Web Developer
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.
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.
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.
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.
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.
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.