Building a Simple E-Commerce Application with Node.js and MongoDB

E-commerce applications have become an integral part of modern businesses. They enable businesses to reach a wider audience, increase their customer base, and streamline their operations. In this article, we will explore how to build a simple e-commerce application with Node.js and MongoDB.

Node.js and MongoDB are popular technologies used for building scalable, fast, and flexible web applications. Node.js is a runtime environment that allows developers to build network applications using JavaScript. MongoDB is a NoSQL database that allows developers to store and manage data in a flexible and scalable way.

Setting up the Environment

To get started, we need to set up our development environment. We will need to have Node.js and MongoDB installed on our computer. We will also need a code editor of our choice, such as Visual Studio Code or Atom.

Creating the Project Structure

Once we have our development environment set up, we can start creating our project structure. We will create a folder for our project and use the command line to navigate to that folder. We will then create a new file called “server.js” in that folder.

Next, we will create a folder called “routes” and another folder called “models”. The “routes” folder will contain our application’s routes, while the “models” folder will contain our application’s data models.

We will also create a file called “.env” to store our environment variables.

Installing Dependencies

We will need to install several dependencies for our application to work. We can do this by running the following command in the terminal:

css
npm install express body-parser cors dotenv mongoose

This command installs the Express framework, which we will use to create our server. It also installs body-parser, which we will use to parse incoming request bodies. The cors package allows cross-origin resource sharing, and dotenv is used to load environment variables. Finally, we will install Mongoose, which is a MongoDB object modeling tool.

Creating the Server

In our “server.js” file, we will start by importing the necessary packages and setting up our environment variables:

javascript
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');

const app = express();
const port = process.env.PORT || 3000;

Next, we will connect to our MongoDB database using Mongoose:

php
mongoose.connect(process.env.DB_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

We will also define a basic route for our application:

javascript
app.get('/', (req, res) => {
  res.send('Hello World!');
});

We can test our server by running the following command in the terminal:

node server.js

If everything is set up correctly, we should see “Hello World!” displayed in our browser when we navigate to http://localhost:3000/.

Creating the Routes and Models

Next, we will create our application’s routes and models. We will start by creating a new file called “product.js” in the “routes” folder. This file will contain our application’s product routes:

javascript
const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
  // Get all products from the database
});

router.post('/', (req, res) => {
  // Add a new product to the database
});

router.put('/:id', (req, res) => {
  // Update a product in the database
});

router.delete('/:id', (req, res) => {
  // Delete a product from the database
});

module.exports = router;

We will also create a new file called “product.js” in the “models” folder.

Creating the Routes and Models (Continued)

php
const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  price: {
    type: Number,
    required: true,
  },
  description: {
    type: String,
    required: true,
  },
});

module.exports = mongoose.model('Product', productSchema);

This code defines a product model with three fields: name, price, and description.

Next, we will update our “product.js” routes file to use our product model:

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

router.get('/', async (req, res) => {
  const products = await Product.find();
  res.send(products);
});

router.post('/', async (req, res) => {
  const product = new Product(req.body);
  await product.save();
  res.send(product);
});

router.put('/:id', async (req, res) => {
  const product = await Product.findByIdAndUpdate(req.params.id, req.body, {
    new: true,
  });
  res.send(product);
});

router.delete('/:id', async (req, res) => {
  const product = await Product.findByIdAndDelete(req.params.id);
  res.send(product);
});

module.exports = router;

This code defines four routes: GET, POST, PUT, and DELETE. The GET route retrieves all products from the database. The POST route adds a new product to the database. The PUT route updates an existing product in the database. The DELETE route deletes a product from the database.

Using the Routes in Our Server

Finally, we will update our “server.js” file to use our product routes:

javascript
const productRoutes = require('./routes/product');

app.use(bodyParser.json());
app.use(cors());

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

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

This code adds middleware for parsing incoming request bodies and enabling cross-origin resource sharing. It then adds our product routes to the application, which are accessible at http://localhost:3000/products.

Conclusion

In this article, we explored how to build a simple e-commerce application with Node.js and MongoDB. We started by setting up our development environment and creating our project structure. We then installed the necessary dependencies and created our server. We also created our application’s routes and models, and used those routes in our server. With these basic building blocks in place, we can now expand our application to include more functionality and features.

0368826868