Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

191 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

e-commerce-Backend

⚑ Dynamic Node.js E-Commerce REST API Engine πŸš€ | Express.js ⚑, MongoDB Atlas πŸ—„οΈ, Mongoose πŸƒ & JWT Auth πŸ” | Scalable MVC Architecture πŸ›οΈ | Secured Auth Middleware πŸ›‘οΈ, Product, User & Review CRUD πŸ›οΈπŸ‘€β­ & .env Protection πŸ—οΈ | High-Performance Scalability πŸ“ˆπŸ’₯


πŸ› οΈ Key Technologies & Core Concepts

  • Backend Architecture: Modular RESTful APIs engineered with Node.js & Express.js, structured using Express Routers, custom middleware error handlers (asyncErrorHandler), and controller-based business logic.
  • Database Persistence & Data Modeling: Scalable document modeling via MongoDB & Mongoose, featuring schema validations, sub-documents (reviews & user roles), and optimized queries (findByIdAndUpdate array updates, returnDocument standards).
  • Security & Error Handling: Robust exception management using global handlers for uncaught exceptions, unhandled promise rejections, and custom error middleware.
  • Environment & Configuration Setup: Centralized setup using dotenv for secret and environment management, proper load ordering, and clean project architecture.
  • Software Architecture: Strictly structured following the MVC (Model-View-Controller) patternβ€”separating Mongoose Data Models, Express Route Handlers, and Controller Business Logic for high maintainability and scalability.

πŸ’‘ What's Inside This Repository?

This workspace contains a production-ready, full-stack E-Commerce REST API backend featuring modular architecture and robust data handling:

  • πŸ›’ E-Commerce REST API: Complete backend infrastructure for products, orders, user authentication, and system administration.
  • βš™οΈ Advanced CRUD & Sub-Document Operations: Complete lifecycle management for products and reviews, including nested array updates via $pull and automatic rating recalculations.
  • πŸ›‘οΈ Role-Based Access Control: Secure user management and admin privilege routing for user roles and product modifications.
  • ⚑ Centralized Error Handling: Global error catching for async controllers, uncaught exceptions, unhandled promise rejections, and custom error middleware.

✨ Features

  • πŸ—οΈ Modular REST API Architecture – Scalable Node.js & Express.js backend engineered with RESTful principles and clean route-controller separation.
  • πŸ›οΈ MVC Design Pattern – Strict separation of concerns organizing data structure in Models, endpoints in Routes, and core application logic in Controllers.
  • βš™οΈ Advanced Database CRUD & Array Operations – Complete lifecycle management for products, users, and reviews, utilizing Mongoose sub-document filtering and dynamic rating recalculations.
  • πŸ›‘οΈ Role-Based Access Control (RBAC) – Multi-role authorization layers restricting sensitive administrative endpoints and user operations.
  • πŸ—„οΈ MongoDB & Mongoose Schema Validation – Persistent document storage featuring custom field validations, schema constraints, and modern Mongoose query standards (returnDocument).
  • ⚑ Centralized Global Error Handling – Production-grade error middleware handling asynchronous route errors (asyncErrorHandler), missing resource exceptions, unhandled promise rejections, and uncaught exceptions.
  • βš™οΈ Centralized Environment Configuration – Secure management of sensitive backend credentials, database URIs, and server ports using dotenv.

πŸ› οΈ Tech Stack & Dependencies

Tool / Library Type Purpose
Node.js Runtime Server-side JavaScript execution environment
Express.js Backend Framework Web framework for handling RESTful API routes & HTTP requests
Mongoose Backend ODM Schema-based data modeling and async queries for MongoDB
Nodemon Dev Dependency Automatically restarts Node app when server-side file changes occur
dotenv Utility Loads environment variables from .env file into process.env
jsonwebtoken (JWT) Dependency Authentication mechanism using secure JSON Web Tokens
bcryptjs Dependency Password hashing library for secure credential storage
nodemailer Dependency Email sending service for user notifications / password resets
validator Dependency String validation and sanitization (e.g., checking valid email formats)
cookie-parser Dependency Middleware to parse HTTP request cookies for auth session handling
body-parser Dependency Middleware to parse incoming request bodies before handlers
Postman API Client Manual testing tool for REST endpoints (GET, POST, PUT, DELETE)

πŸ“‚ Project Directory Structure

Generated: 8/12/2026, 10:41:29 AM

Root Path: workspace\e-commerce-Backend

β”œβ”€β”€ πŸ“ backend
β”‚   β”œβ”€β”€ πŸ“ config
β”‚   β”œβ”€β”€ πŸ“ controllers
β”‚   β”‚   β”œβ”€β”€ πŸ“„ productController.js
β”‚   β”‚   └── πŸ“„ userController.js
β”‚   β”œβ”€β”€ πŸ“ middlewares
β”‚   β”‚   β”œβ”€β”€ πŸ“„ asyncErrorHandler.js
β”‚   β”‚   β”œβ”€β”€ πŸ“„ auth.js
β”‚   β”‚   └── πŸ“„ error.js
β”‚   β”œβ”€β”€ πŸ“ models
β”‚   β”‚   β”œβ”€β”€ πŸ“„ productModel.js
β”‚   β”‚   └── πŸ“„ userModel.js
β”‚   β”œβ”€β”€ πŸ“ routes
β”‚   β”‚   β”œβ”€β”€ πŸ“„ productRoute.js
β”‚   β”‚   └── πŸ“„ userRoute.js
β”‚   β”œβ”€β”€ πŸ“ utils
β”‚   β”‚   β”œβ”€β”€ πŸ“„ ApiFeatures.js
β”‚   β”‚   β”œβ”€β”€ πŸ“„ Errorhandler.js
β”‚   β”‚   β”œβ”€β”€ πŸ“„ JWTToken.js
β”‚   β”‚   └── πŸ“„ sendEmail.js
β”‚   β”œβ”€β”€ πŸ“„ app.js
β”‚   β”œβ”€β”€ πŸ“„ connectDB.js
β”‚   └── πŸ“„ server.js
β”œβ”€β”€ πŸ“ frontend
β”‚   └── βš™οΈ .gitkeep
β”œβ”€β”€ βš™οΈ .gitignore
β”œβ”€β”€ πŸ“ README.md
β”œβ”€β”€ βš™οΈ package-lock.json
└── βš™οΈ package.json

πŸš€ Getting Started

Prerequisites

  • Node.js (v16 or higher)
  • npm package manager
  • Basic knowledge of JavaScript & MongoDB

πŸ“¦ MERN Stack: Backend Architecture Setup Guide

1. Installing Node.js & NPM

Download and install the LTS version from Node.js Official Site. Verify installation in your terminal:

node -v
npm -v

2. Installing MongoDB Community Server & Mongosh

  1. Download MongoDB Community Server from MongoDB Download Center.
  2. Download MongoDB Shell (mongosh) to run CLI database operations.
  3. Start the local server daemon:
# Verify connection using mongosh CLI
mongosh

3. Setting Up package.json with ES Modules

Initialize your Node project inside any project directory:

npm init

During the prompt configuration, fill out the selections like this:

package name: (name)

version: (1.0.0)

description: may add ​ entry point: (app.js)​

test command: just enter​

git repository: (https://github.com/username/repo_name.git)

keywords: may add

author: may add

license: (ISC) may be MIT for open source

type: (commonjs) recommended module

Is this OK? (yes)


πŸ’» How to Run the backend of the MERN Project Locally

If you want to pull this project and run it again locally, simply execute these commands:

# Navigate to the project folder
cd Project_dir

# create node_modules folder by running this command  
npm i

# Start the local development server
npm start  # for deployment 
npm run dev # for development

To enable modern ES6 import/export syntax instead of require(), open package.json and add "type": "module":

{
  "name": "node",
  "version": "1.0.0",
  "bugs": {
    "url": "https://github.com/username/repo/issues"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/username/repo.git"
  },
  "license": "ISC",
  "author": "",
  "type": "commonjs",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app.js" // add manually write "nodemon index.js" if installed
  }
}

4. Installing Core Dependencies for MERN Stack Backend

Run this command inside your project directory to install npm pakages in pakages.json file:

npm i express
npm i mongoose
npm i nodemon
npm i dotenv
npm i jsonwebtoken
npm i nodemailer
npm i bcryptjs
npm i validator
npm i cookie-parser
npm i body-parser

It automatically Create package.json if not exists. Like

{
  "name": "pakage name",
  "version": "1.0.0",
  "description": "Something",
  "keywords": [
    "keywords"
  ],
  "homepage": "https://github.com/github.com/username#readme",
  "bugs": {
    "url": "https://github.com/github.com/username/issues"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/github.com/username.git"
  },
  "author": "Author",
  "type": "module",
   "main": "backend/server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node backend/server.js",
    "dev": "nodemon backend/server.js"
  },
  "dependencies": {
    "bcryptjs": "^3.0.3",
    "body-parser": "^2.3.0",
    "cookie-parser": "^1.4.7",
    "dotenv": "^17.4.2",
    "express": "^5.2.1",
    "jsonwebtoken": "^9.0.3",
    "mongoose": "^9.9.1",
    "nodemailer": "^9.0.5",
    "nodemon": "^3.1.14",
    "validator": "^13.15.35"
  }
}

Note: Install packages when needed


πŸš€ E-Commerce REST API - Routing & Setup Guide

A production-ready Node.js & Express RESTful API architecture following the MVC (Model-View-Controller) pattern with JWT Authentication, Role-Based Access Control (RBAC), and Mongoose sub-document query handling.


Installation Steps

# Clone the repository
git clone [https://github.com/YOUR_USERNAME/YOUR_REPO_NAME.git](https://github.com/YOUR_USERNAME/YOUR_REPO_NAME.git)

# Navigate to backend directory
cd backend

# Install dependencies
npm install

# Configure Environment Variables (.env)
# Create a .env file in the config/ directory with:
PORT=5000
DB_URI=mongodb://localhost:27017/ecommerce
JWT_SECRET=YOUR_JWT_SECRET_KEY
JWT_EXPIRE=nd
COOKIE_EXPIRE=n
SMPT_HOST=host
SMPT_PORT=port
SMPT_SERVICE=service
SMPT_MAIL=your_email@gmail.com
SMPT_PASSWORD=your_app_password

🌐 API Route Specifications

Base Route: protocol://host:port/api/v1


1. User & Authentication Routes (/api/v1)

Method Endpoint Access Level Description
POST /register Public Register a new user and generate JWT token in HTTP-only cookie
POST /login Public Authenticate existing user credentials
GET /logout Public Clear session cookie and end user session
POST /password/forgot Public Generate password reset token & email recovery link
PUT /password/reset/:token Public Update user password using validated reset token
GET /me Authenticated Fetch current logged-in user profile details
PUT /password/update Authenticated Update account password using current password validation
PUT /me/update Authenticated Update basic profile information (Name, Email)
GET /admin/users Admin Only Fetch list of all registered users in database
GET /admin/user/:id Admin Only Get single user detail by MongoDB ObjectId
PUT /admin/user/:id Admin Only Update user role (admin / user) and details
DELETE /admin/user/:id Admin Only Permanently delete user account from database

2. Product & Review Routes (/api/v1)

Method Endpoint Access Level Description
GET /products Public Fetch products with Search, Filter, and Pagination features
GET /products/:id Public Get single product detail by ObjectId
POST /admin/products/create Admin Only Create new product catalog item
PUT /admin/products/:id Admin Only Update product details
DELETE /admin/products/:id Admin Only Delete product record from database
PUT /review Authenticated Create or update user review & recalculate average ratings
GET /reviews?id=PRODUCT_ID Public Fetch all reviews belonging to a specific product
DELETE /reviews?productId=P_ID&id=R_ID Authenticated Delete a sub-document review & recalculate overall rating

⚠️ Troubleshooting Common Pitfalls

  • Review Sub-Document Deletion (_id Mismatch): When deleting a review via DELETE /api/v1/reviews?productId=P_ID&id=R_ID, ensure the id query parameter corresponds to the Review Sub-Document _id, not the User _id. Passing the User ID will cause Mongoose filter operations to skip without mutating the database array.

πŸ“š Learning Resources


πŸ’‘ Core Concepts Covered

  • βœ… MVC Architecture – Structuring backend applications using Models, Express Routes, and Controller business logic
  • βœ… Authentication & JWT – Issuing, signing, and verifying JSON Web Tokens (JWT) for secure user sessions
  • βœ… Password Security & Hashing – Hashing user credentials securely using bcryptjs before database persistence
  • βœ… Cookie Management – Storing and parsing HTTP-only cookies safely with cookie-parser for authentication state
  • βœ… Role-Based Access Control (RBAC) – Dynamic route protection and administrative privilege checks based on user roles
  • βœ… MongoDB & Mongoose Schema Design – Managing schemas, data validation, sub-documents (reviews), and modern Mongoose query standards
  • βœ… Sub-Document & Array Operations – Atomic array updates ($pull) and dynamic calculation of ratings and review counts
  • βœ… Express Middleware Pipeline – Request body parsing (json, urlencoded), error handling middleware, and protected route guards
  • βœ… Asynchronous Error Handling – Managing async exceptions cleanly with custom error handlers (asyncErrorHandler) and custom error classes
  • βœ… Notification Services – Integrated email workflows using Nodemailer for user notifications and password resets
  • βœ… Environment Vault & Tooling – Managing secret variables via dotenv and developer workflows with nodemon

πŸ‘€ Author

MehmoodCoder


πŸ“„ License

This project is open-source and available under the MIT License.


🀝 Contributing

Contributions are welcome! If you'd like to improve the API, add new features, or optimize database queries, please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“ Changelog

v1.0.0 (Initial Release)

  • ✨ Modular REST API Architecture: Initialized core Node.js & Express.js backend services structured around the MVC pattern.
  • πŸ” Authentication & Authorization: Implemented JWT-based security, password hashing with bcryptjs, and role-based access control middleware.
  • βš™οΈ Advanced CRUD Systems & Array Operations: Engineered complete backend routes for product management, user profiles, and sub-document review handling (filters).
  • ⚑ Global Error Handling: Integrated custom async error handler and global error middleware for robust exception management.
  • πŸ—„οΈ Database Persistence: Configured Mongoose schema designs with strict validation rules and cloud MongoDB Atlas connectivity.
  • πŸš€ Production-Ready Baseline: Configured environment isolation via dotenv, cookie-parser session management, and serverless deployment protocols.

Happy coding without chai ! β˜•

About

⚑ Dynamic Node.js E-Commerce REST API Engine πŸš€ | Express.js ⚑, MongoDB πŸ—„οΈ, Mongoose πŸƒ & JWT Auth πŸ” | Scalable MVC Architecture πŸ›οΈ | Secured Auth Middleware πŸ›‘οΈ, Product & Order CRUD πŸ›οΈπŸ“¦, Cart Engine πŸ›’πŸ’³ & `.env` Protection πŸ—οΈ | High-Performance Scalability πŸ“ˆπŸ’₯

Topics

Resources

Stars

14 stars

Watchers

0 watching

Forks

Contributors

Languages