logo

Case Study: E-Commerce Application

Developed Using MVC Pattern with MERN Stack

This case study explores the development of an e-commerce application using the MERN stack (MongoDB, Express.js, React.js, and Node.js) while implementing the MVC (Model-View-Controller) architectural pattern. The goal is to demonstrate how the MVC pattern can be effectively utilized in a MERN-based project to create a scalable and maintainable e-commerce platform.

Project Overview
  • Application Name: ShopEase
  • Objective: To create a full-featured e-commerce application that allows users to browse products, add items to their cart, and complete purchases, while providing admin functionality to manage products and orders.
Technologies Used
  • Frontend: React.js
  • Backend: Node.js with Express.js
  • Database: MongoDB
  • Architecture: MVC Pattern
  • Additional Tools: Redux (for state management), Mongoose (for MongoDB object modeling), JWT (for authentication), and Bootstrap (for UI styling).
MVC Architecture
  • Model: Represents the data structure. For this project, Mongoose models are used to define the schema for products, users, and orders.
  • View: The user interface. React components are used to create dynamic and responsive views.
  • Controller: Handles the logic and user input. Express.js routes act as controllers to process requests and interact with models.
Application Features
User Features:
  • User Registration and Authentication:

    • Users can register, log in, and log out.
    • Passwords are hashed using bcrypt, and JWTs are used for session management.
  • Product Browsing and Search:

    • Users can view a list of products.
    • Search functionality to filter products based on keywords.
  • Product Details:

    • Detailed view of each product, including images, descriptions, and reviews.
  • Shopping Cart:

    • Users can add, update, and remove products in their cart.
    • The cart is persisted in local storage to maintain state across sessions.
  • Checkout and Order Placement:

    • Users can enter shipping information and payment details.
    • Orders are saved in the database and users receive order confirmation.
Admin Features:
  • Product Management:

    • Admins can add, edit, and delete products.
    • Product management views are accessible only to authenticated admin users.
  • Order Management:

    • Admins can view all orders.
    • Update order statuses (e.g., processing, shipped, delivered).
Implementation Details
Model Layer
  • User Model:

    Defines user schema including username, email, password, and role.
  • Product Model:

    Defines product schema including name, price, description, category, and stock quantity.
  • Order Model:

    Defines order schema including user, order items, shipping address, payment method, and order status.
             
// User Model (models/User.js)
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const userSchema = mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
isAdmin: { type: Boolean, default: false }
}, {
timestamps: true
});
userSchema.methods.matchPassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
};
const User = mongoose.model('User', userSchema);
module.exports = User;
             
            
View Layer

React Components: Structured in a way that separates concerns, with components for the homepage, product listing, product details, cart, and admin dashboard.

Redux: Used for managing application state, including user authentication status, product data, and cart contents.

                
// ProductList Component (components/ProductList.js)
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { listProducts } from '../actions/productActions';
import Product from './Product';
const ProductList = () => {
const dispatch = useDispatch();
const productList = useSelector((state) => state.productList);
const { loading, error, products } = productList;
useEffect(() => {
dispatch(listProducts());
}, [dispatch]);
return (            
{loading ? (
 Loading...
 ) : error ? (
      {error}
) : (
{products.map((product) => ( ))}
)} ); }; export default ProductList;
Controller Layer

Express Routes: Define API endpoints for handling CRUD operations on products, user authentication, and order processing.

Middleware: JWT middleware for protecting routes that require authentication.

                
// Product Controller (controllers/productController.js)
const asyncHandler = require('express-async-handler');
const Product = require('../models/Product');
// @desc    Fetch all products
// @route   GET /api/products
// @access  Public
const getProducts = asyncHandler(async (req, res) => {
 const products = await Product.find({});
res.json(products);
});
// @desc    Fetch single product
// @route   GET /api/products/:id
// @access  Public
const getProductById = asyncHandler(async (req, res) => {
 const product = await Product.findById(req.params.id);
if (product) {
 res.json(product);
} else {
 res.status(404);
throw new Error('Product not found');
}
});
module.exports = {
getProducts,
getProductById,
};
          
         

Integrating the Layers

1. Frontend and Backend Connection
  • Use Axios for making HTTP requests from React to Express.
  • Set up Redux actions and reducers to handle asynchronous data fetching.
2. Authentication Middleware
  • Protect routes by checking for valid JWTs.
  • Redirect unauthorized users to the login page
3. Database Interaction
  • Mongoose is used to interact with MongoDB, providing a straightforward way to perform CRUD operations.

Conclusion

This e-commerce application case study demonstrates the practical implementation of the MVC pattern using the MERN stack. By separating concerns into models, views, and controllers, the application remains modular, scalable, and maintainable. This approach allows developers to manage complex application logic while providing a responsive and dynamic user experience.

Whatsapp+
LinkedIn
Instagram
Facebook
Youtube