continuous_2
continuous_2
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
• Node.js
• MongoDB
• npm (Node Package Manager)
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
product-sales/
├── models/
│ └── Product.js
├── routes/
│ └── productRoutes.js
├── app.js
└── package.json
Explanation:
Creating Routes
// 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:
In the app.js file, set up the Express server and connect to MongoDB:
// 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.
mongod
node app.js
You can use tools like Postman or curl to test the API endpoints:
• Create a product:
```bash
POST http://localhost:3000/api/products
"price": 100,
"quantity": 10
```
```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.