:file_folder: Day 50: Structuring a MERN Project for Scalability :rocket:

The MERN stack (MongoDB, Express.js, React, Node.js) is great for building full-stack apps, but if your project is poorly structured, it will lead to bugs, messy code, and maintenance nightmares.

A well-structured backend makes your code more scalable, readable, and secure. This post will guide you through structuring your MERN backend properly using the MVC (Model-View-Controller) pattern.

:one: Why Structure Your Backend Properly?
:small_blue_diamond: Separation of concerns → Business logic is separate from database & routes
:small_blue_diamond: Scalability → Adding features is easy
:small_blue_diamond: Better collaboration → Multiple developers can work efficiently
Recommended Folder Structure

/server
├── controllers/ → Handles logic
├── models/ → Defines data structure
├── routes/ → API endpoints
├── middleware/ → Security & validation
├── config/ → Database & environment variables
├── utils/ → Reusable helper functions
├── index.js → Main server file

:two: Models: Defining Data Structure
Models define how data is stored in MongoDB.
Example: User Model (models/User.js)
Defines user schema
Encrypts passwords
Adds timestamps automatically
:small_red_triangle_down:
const mongoose = require(‘mongoose’);
const UserSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
role: { type: String, enum: [“user”, “admin”], default: “user” }
}, { timestamps: true });
module.exports = mongoose.model(“User”, UserSchema);
:small_red_triangle:
:three: Controllers: Handling Business Logic
Controllers process requests and interact with models.
Example: User Controller (controllers/userController.js)
:small_blue_diamond: Registers a user
:small_blue_diamond: Hashes passwords
:small_blue_diamond: Handles login authentication
:small_red_triangle_down:
const User = require(‘…/models/User’);
const bcrypt = require(‘bcrypt’);
const jwt = require(‘jsonwebtoken’);
exports.registerUser = async (req, res) => {
try {
//Code Logic Here
} catch (error) { res.status(500).json({ error: error.message }); }
};
:small_red_triangle:
:four: Routes: Managing API Endpoints
Routes define API paths and call controllers.
Example: User Routes (routes/userRoutes.js)
:small_blue_diamond: Links API endpoints to controllers
:small_blue_diamond: Keeps routing separate from business logic
:small_red_triangle_down:
const express = require(‘express’);
const { registerUser, loginUser } = require(‘…/controllers/userController’);
const router = express.Router();
router.post(‘/register’, registerUser);
router.post(‘/login’, loginUser);
module.exports = router;
:small_red_triangle:
:five: Bringing It All Together: The Main Server File (index.js)
:small_blue_diamond: Loads environment variables
:small_blue_diamond: Connects to MongoDB
:small_blue_diamond: Sets up routes

100daysofcode lebanon-mug