β‘ 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 ππ₯
- 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 (
findByIdAndUpdatearray updates,returnDocumentstandards). - 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
dotenvfor 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.
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
$pulland 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.
- ποΈ 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.
| 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) |
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
- Node.js (v16 or higher)
- npm package manager
- Basic knowledge of JavaScript & MongoDB
Download and install the LTS version from Node.js Official Site. Verify installation in your terminal:
node -v
npm -v- Download MongoDB Community Server from MongoDB Download Center.
- Download MongoDB Shell (
mongosh) to run CLI database operations. - Start the local server daemon:
# Verify connection using mongosh CLI
mongoshInitialize your Node project inside any project directory:
npm initpackage 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)
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 developmentTo 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
}
}
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-parserIt 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
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.
# 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
Base Route: protocol://host:port/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 |
| 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 |
- Review Sub-Document Deletion (
_idMismatch): When deleting a review viaDELETE /api/v1/reviews?productId=P_ID&id=R_ID, ensure theidquery 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.
- Express.js Documentation β (Official guide for routing, controllers, and Express middleware)
- Mongoose Documentation β (Guides for MongoDB schema modeling, queries, and aggregation)
- JSON Web Token (JWT) Guide β (Official docs for token-based authentication and security)
- Bcryptjs Repository β (Documentation for hashing passwords securely in Node.js)
- Nodemailer Documentation β (Official setup guide for sending emails and password resets)
- Cookie-Parser Repository β (Guide for parsing HTTP request cookies in Express)
- Validator.js Documentation β (Reference for string sanitization and custom schema validation)
- Postman Learning Center β (API testing, collection management, and request debugging)
- W3Schools Web Tutorials β (Comprehensive tutorials for JavaScript, Node.js, Express, and databases)
- β 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
bcryptjsbefore database persistence - β
Cookie Management β Storing and parsing HTTP-only cookies safely with
cookie-parserfor 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
Nodemailerfor user notifications and password resets - β
Environment Vault & Tooling β Managing secret variables via
dotenvand developer workflows withnodemon
MehmoodCoder
- π GitHub: https://github.com/MehmoodCoder
- π Portfolio: My Portfolio Link
This project is open-source and available under the MIT License.
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.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- β¨ 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.