In this section, we will explore how to build an e-commerce application using MongoDB. This will include designing the database schema, implementing CRUD operations, and integrating MongoDB with a web application. By the end of this section, you will have a solid understanding of how to use MongoDB in a real-world e-commerce scenario.

  1. Database Schema Design

Key Collections

  1. Users: Stores user information.
  2. Products: Stores product details.
  3. Orders: Stores order information.
  4. Reviews: Stores product reviews.

Schema Design

Users Collection

{
  "_id": "ObjectId",
  "username": "string",
  "email": "string",
  "password": "string",
  "address": {
    "street": "string",
    "city": "string",
    "state": "string",
    "zip": "string"
  },
  "createdAt": "date"
}

Products Collection

{
  "_id": "ObjectId",
  "name": "string",
  "description": "string",
  "price": "number",
  "category": "string",
  "stock": "number",
  "createdAt": "date"
}

Orders Collection

{
  "_id": "ObjectId",
  "userId": "ObjectId",
  "products": [
    {
      "productId": "ObjectId",
      "quantity": "number"
    }
  ],
  "totalPrice": "number",
  "status": "string",
  "createdAt": "date"
}

Reviews Collection

{
  "_id": "ObjectId",
  "productId": "ObjectId",
  "userId": "ObjectId",
  "rating": "number",
  "comment": "string",
  "createdAt": "date"
}

  1. Implementing CRUD Operations

Creating Documents

Create a New User

db.users.insertOne({
  "username": "john_doe",
  "email": "[email protected]",
  "password": "hashed_password",
  "address": {
    "street": "123 Main St",
    "city": "Anytown",
    "state": "CA",
    "zip": "12345"
  },
  "createdAt": new Date()
});

Create a New Product

db.products.insertOne({
  "name": "Laptop",
  "description": "A high-performance laptop",
  "price": 999.99,
  "category": "Electronics",
  "stock": 50,
  "createdAt": new Date()
});

Reading Documents

Find a User by Username

db.users.findOne({ "username": "john_doe" });

Find All Products in a Category

db.products.find({ "category": "Electronics" });

Updating Documents

Update Product Stock

db.products.updateOne(
  { "_id": ObjectId("product_id") },
  { $set: { "stock": 45 } }
);

Deleting Documents

Delete a User by ID

db.users.deleteOne({ "_id": ObjectId("user_id") });

  1. Integrating MongoDB with a Web Application

Setting Up the Environment

  1. Node.js: We will use Node.js for the backend.
  2. Express.js: A web framework for Node.js.
  3. Mongoose: An ODM (Object Data Modeling) library for MongoDB and Node.js.

Example: Setting Up a Basic Express Server

Install Dependencies

npm install express mongoose

Create server.js

const express = require('express');
const mongoose = require('mongoose');

const app = express();
const port = 3000;

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/ecommerce', { useNewUrlParser: true, useUnifiedTopology: true });

// Middleware
app.use(express.json());

// Routes
app.get('/', (req, res) => {
  res.send('Welcome to the E-commerce API');
});

// Start Server
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

Example: Creating a Product API

Define Product Model

const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
  name: String,
  description: String,
  price: Number,
  category: String,
  stock: Number,
  createdAt: { type: Date, default: Date.now }
});

const Product = mongoose.model('Product', productSchema);

module.exports = Product;

Create Product Routes

const express = require('express');
const router = express.Router();
const Product = require('./models/Product');

// Create a new product
router.post('/products', async (req, res) => {
  const product = new Product(req.body);
  try {
    await product.save();
    res.status(201).send(product);
  } catch (error) {
    res.status(400).send(error);
  }
});

// Get all products
router.get('/products', async (req, res) => {
  try {
    const products = await Product.find();
    res.status(200).send(products);
  } catch (error) {
    res.status(500).send(error);
  }
});

module.exports = router;

Integrate Routes in server.js

const productRoutes = require('./routes/products');

app.use('/api', productRoutes);

  1. Practical Exercises

Exercise 1: Add a New User

  1. Create a new user document in the users collection.
  2. Verify the user is added by querying the users collection.

Exercise 2: Update Product Price

  1. Update the price of a specific product.
  2. Verify the price is updated by querying the products collection.

Exercise 3: Delete an Order

  1. Delete an order document from the orders collection.
  2. Verify the order is deleted by querying the orders collection.

Solutions

Solution 1: Add a New User

db.users.insertOne({
  "username": "jane_doe",
  "email": "[email protected]",
  "password": "hashed_password",
  "address": {
    "street": "456 Elm St",
    "city": "Othertown",
    "state": "NY",
    "zip": "67890"
  },
  "createdAt": new Date()
});

Solution 2: Update Product Price

db.products.updateOne(
  { "_id": ObjectId("product_id") },
  { $set: { "price": 899.99 } }
);

Solution 3: Delete an Order

db.orders.deleteOne({ "_id": ObjectId("order_id") });

Conclusion

In this section, we covered how to design a database schema for an e-commerce application, implement CRUD operations, and integrate MongoDB with a web application using Node.js and Express. We also provided practical exercises to reinforce the concepts learned. This knowledge will be invaluable as you build and scale real-world applications using MongoDB.

© Copyright 2024. All rights reserved