0% found this document useful (0 votes)
16 views

continuous_2

This document provides a step-by-step guide to creating a CRUD application for managing product sales using Express.js and Mongoose. It covers project setup, Mongoose model creation, route definitions for CRUD operations, and connecting to a MongoDB database. The application allows users to add, retrieve, update, and delete products, serving as a foundation for more complex features in the future.

Uploaded by

SAAD TRA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

continuous_2

This document provides a step-by-step guide to creating a CRUD application for managing product sales using Express.js and Mongoose. It covers project setup, Mongoose model creation, route definitions for CRUD operations, and connecting to a MongoDB database. The application allows users to add, retrieve, update, and delete products, serving as a foundation for more complex features in the future.

Uploaded by

SAAD TRA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Express Mongoose CRUD for Product Sales

This document outlines the creation of a simple CRUD (Create, Read, Update, Delete)
application for managing product sales using Express.js and Mongoose. The application will
allow users to perform operations on a product sales database, including adding new
products, retrieving product information, updating existing products, and deleting products.
We will also explain each step of the process to ensure clarity.

Prerequisites

Before we begin, ensure you have the following installed:

• Node.js
• MongoDB
• npm (Node Package Manager)

Setting Up the Project


1. Initialize a new Node.js project:

Open your terminal and create a new directory for your project. Navigate into the directory
and run:

mkdir product-sales
cd product-sales
npm init -y

2. Install required packages:

Install Express and Mongoose by running:

npm install express mongoose body-parser

3. Create the project structure:

Create the following files and folders:

product-sales/
├── models/
│ └── Product.js
├── routes/
│ └── productRoutes.js
├── app.js
└── package.json

Setting Up Mongoose Model

In the models/Product.js file, define the Product schema:

const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({


name: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
quantity: {
type: Number,
required: true
}
});

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

Explanation:

• We import Mongoose and define a schema for our products.


• Each product has a name, price, and quantity, all of which are required fields.

Creating Routes

In the routes/productRoutes.js file, set up the CRUD routes:

const express = require('express');


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

// Create a new product


router.post('/', async (req, res) => {
const product = new Product(req.body);
try {
const savedProduct = await product.save();
res.status(201).json(savedProduct);
} catch (err) {
res.status(400).json({ message: err.message });
}
});

// Get all products


router.get('/', async (req, res) => {
try {
const products = await Product.find();
res.json(products);
} catch (err) {
res.status(500).json({ message: err.message });
}
});

// Update a product
router.patch('/:id', async (req, res) => {
try {
const updatedProduct = await Product.findByIdAndUpdate(req.params.id,
req.body, { new: true });
res.json(updatedProduct);
} catch (err) {
res.status(400).json({ message: err.message });
}
});

// Delete a product
router.delete('/:id', async (req, res) => {
try {
await Product.findByIdAndDelete(req.params.id);
res.status(204).send();
} catch (err) {
res.status(500).json({ message: err.message });
}
});

module.exports = router;

Explanation:

• We define routes for creating, reading, updating, and deleting products.


• Each route handles requests and responses, using async/await for asynchronous
operations.

Setting Up the Express Application

In the app.js file, set up the Express server and connect to MongoDB:

const express = require('express');


const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const productRoutes = require('./routes/productRoutes');

const app = express();


const PORT = process.env.PORT || 3000;

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

// MongoDB connection
mongoose.connect('mongodb://localhost:27017/productSales', { useNewUrlParser:
true, useUnifiedTopology: true })
.then(() => console.log('MongoDB connected'))
.catch(err => console.error(err));

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

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

Explanation:

• We import the necessary modules and set up middleware to parse JSON requests.
• We connect to a local MongoDB database named productSales.
• We define the base route for our product API and start the server.

Running the Application


1. Start MongoDB:

Ensure your MongoDB server is running. You can start it using:

mongod

2. Run the Express application:

In your terminal, run:

node app.js

3. Test the API:

You can use tools like Postman or curl to test the API endpoints:

• Create a product:

```bash

POST http://localhost:3000/api/products

"name": "Product A",

"price": 100,

"quantity": 10

```

• Get all products:

```bash

GET http://localhost:3000/api/products

```

• Update a product:

```bash

PATCH http://localhost:3000/api/products/{id}

"price": 120

```

• Delete a product:

```bash

DELETE http://localhost:3000/api/products/{id}

```

Conclusion

In this document, we have created a simple CRUD application for managing product sales
using Express and Mongoose. We defined a product model, set up routes for CRUD
operations, and connected to a MongoDB database. This application serves as a foundation
for building more complex features and functionalities in the future.

You might also like