4. Models
Table of Contents
Introduction
This tutorial provides a step-by-step guide to building models for an eCommerce application using Node.js and Express. Focusing on the MVC architecture, we'll cover the creation and organization of models, which are essential for managing data within your application. This guide is particularly useful for those looking to strengthen their backend development skills in a Node.js environment.
Step 1: Setting Up Your Project
- Create a new directory for your eCommerce application:
mkdir ecommerce-app cd ecommerce-app
- Initialize a new Node.js project:
npm init -y
- Install necessary packages:
npm install express mongoose
Step 2: Creating the Model Structure
- Create a new folder named
models
to hold your model files:mkdir models
- Inside the
models
folder, create a file for your product model, e.g.,product.js
.
Step 3: Defining the Product Model
- Open
product.js
and define the schema using Mongoose:const mongoose = require('mongoose'); const productSchema = new mongoose.Schema({ name: { type: String, required: true }, price: { type: Number, required: true }, description: { type: String, required: true }, imageUrl: { type: String, required: true } }); module.exports = mongoose.model('Product', productSchema);
Step 4: Connecting to MongoDB
- In your main application file (e.g.,
app.js
), set up the MongoDB connection:const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/ecommerce', { useNewUrlParser: true, useUnifiedTopology: true }).then(() => { console.log('Connected to MongoDB'); }).catch(err => { console.error('MongoDB connection error:', err); });
Step 5: Using the Model in Routes
- Create a new folder named
routes
and add a file for product routes, e.g.,productRoutes.js
:const express = require('express'); const Product = require('../models/product'); const router = express.Router(); // Route to create a new product router.post('/products', async (req, res) => { const { name, price, description, imageUrl } = req.body; const product = new Product({ name, price, description, imageUrl }); await product.save(); res.status(201).send(product); }); module.exports = router;
Step 6: Integrating Routes into the Application
- In
app.js
, integrate the product routes:const express = require('express'); const productRoutes = require('./routes/productRoutes'); const app = express(); app.use(express.json()); app.use('/api', productRoutes);
Conclusion
In this tutorial, you learned how to set up an eCommerce application using Node.js and Express with a focus on defining models. You created a product model, connected to MongoDB, and integrated routes to handle product data. With these foundational steps complete, you can extend your application by adding more models and features, such as user authentication and order management. Consider exploring additional resources or tutorials to further enhance your backend development skills.