Practical REST API Architecture with Node.js, Express & MongoDB
How to structure maintainable, production-ready backend APIs using layered service patterns, robust input validation, and MongoDB index tuning.

Building scalable backend web services requires more than simply connecting an Express router to a database collection. Without clear structural boundaries, business logic leaks into HTTP controllers, error handling becomes inconsistent, and database queries degrade under scale.
This guide details a layered architectural pattern for Node.js and MongoDB backends that emphasizes maintainability and clean boundaries.
1. The Three-Layer Backend Architecture#
To keep backend codebases maintainable, divide server responsibilities into three distinct tiers:
- Controller Layer: Handles HTTP requests, reads route parameters, performs validation, and formats HTTP responses.
- Service Layer: Contains core business logic, permissions, notifications, and transaction workflows. Independent of Express
reqandresobjects. - Data Access Layer (Repository / Models): Interfaces directly with MongoDB via Mongoose schemas and queries.
// services/issue.service.ts
import { IssueModel, IIssue } from "@/models/issue.model";
export class IssueService {
static async createIssue(userId: string, data: Partial<IIssue>): Promise<IIssue> {
// 1. Business rule validation
const activeCount = await IssueModel.countDocuments({
reporterId: userId,
status: "OPEN",
});
if (activeCount >= 10) {
throw new Error("Maximum concurrent open issues reached.");
}
// 2. Persistent storage
return IssueModel.create({
...data,
reporterId: userId,
status: "OPEN",
createdAt: new Date(),
});
}
}
2. Centralized Error Handling & Async Wrappers#
Avoid wrapping every single route handler in repetitive try/catch blocks. Instead, use an asynchronous error wrapper to forward unhandled exceptions to an Express global error middleware:
// middleware/async-handler.ts
import { Request, Response, NextFunction } from "express";
export const asyncHandler = (fn: Function) => {
return (req: Request, res: Response, next: NextFunction) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
};
This guarantees consistent JSON error payloads, captures uncaught rejections, and keeps controllers concise.
3. MongoDB Indexing & Query Performance#
As application datasets grow, unindexed queries quickly lead to full collection scans (COLLSCAN), causing elevated CPU usage and sluggish response latencies.
Always evaluate your query access patterns:
// models/complaint.schema.ts
import { Schema } from "mongoose";
const complaintSchema = new Schema({
categoryId: { type: String, required: true },
status: { type: String, required: true },
createdAt: { type: Date, default: Date.now },
});
// Compound index for frequent category and status filtering
complaintSchema.index({ categoryId: 1, status: 1 });
4. Key Takeaways#
- Keep Controllers Thin: Controllers should only parse HTTP inputs and delegate business calculations to dedicated services.
- Standardize Responses: Always return consistent JSON structures with clear status codes and error messages.
- Index Access Paths: Monitor query performance and index fields frequently used in sorting, filtering, and foreign keys.
This layered pattern and compound query optimization was implemented in practice in the Our City Nirman Engineering Case Study to handle civic infrastructure tracking and public grievance triage.
