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.
- Database Schema Design
Key Collections
- Users: Stores user information.
- Products: Stores product details.
- Orders: Stores order information.
- 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"
}
- 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
Find All Products in a Category
Updating Documents
Update Product Stock
Deleting Documents
Delete a User by ID
- Integrating MongoDB with a Web Application
Setting Up the Environment
- Node.js: We will use Node.js for the backend.
- Express.js: A web framework for Node.js.
- Mongoose: An ODM (Object Data Modeling) library for MongoDB and Node.js.
Example: Setting Up a Basic Express Server
Install Dependencies
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
- Practical Exercises
Exercise 1: Add a New User
- Create a new user document in the
userscollection. - Verify the user is added by querying the
userscollection.
Exercise 2: Update Product Price
- Update the price of a specific product.
- Verify the price is updated by querying the
productscollection.
Exercise 3: Delete an Order
- Delete an order document from the
orderscollection. - Verify the order is deleted by querying the
orderscollection.
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
Solution 3: Delete an Order
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.
