Express.js is a popular Node.js framework that is widely used for building web applications and APIs. One of the most common operations performed in web development is CRUD (Create, Read, Update, and Delete) operations. In this blog, we'll explore how to perform CRUD operations using Express.js with a simple example of code.
We'll start by creating a new Node.js project and installing the Express.js package using npm. Open up your terminal and run the following command:
npm install express
Once installed, we can create a new file called server.js. In this file, we'll require the Express.js module and create a new instance of the Express.js application.
const express = require('express');
const app = express();
Now, let's create a simple in-memory database using an array of objects. In this example, we'll create a simple "products" database with the following schema:
const products = [
{ id: 1, name: 'Product 1', price: 10.0 },
{ id: 2, name: 'Product 2', price: 20.0 },
{ id: 3, name: 'Product 3', price: 30.0 },
];
With our database in place, we can now start building our CRUD routes.
Create (POST)
To create a new product, we'll create a new route using the app.post() method. This method creates a new route for POST requests.
app.post('/products', (req, res) => {
const { name, price } = req.body;
const id = products.length + 1;
const newProduct = { id, name, price };
products.push(newProduct);
res.status(201).json(newProduct);
});
In this example, we're creating a new route for the /products endpoint and using the req.body object to extract the name and price of the new product. We're then generating a new ID for the product and adding it to the products array. Finally, we're returning the newly created product in the response with a status code of 201.
Read (GET)
To read products from the database, we'll create a new route using the app.get() method. This method creates a new route for GET requests.
app.get('/products', (req, res) => {
res.json(products);
});
In this example, we're creating a new route for the **/products **endpoint and returning the entire products array in the response.
We can also create a route to retrieve a single product by ID.
app.get('/products/:id', (req, res) => {
const { id } = req.params;
const product = products.find(p => p.id === parseInt(id));
if (!product) {
return res.status(404).json({ message: 'Product not found' });
}
res.json(product);
});
In this example, we're creating a new route for the /products/:id endpoint, where :id **is a parameter that represents the ID of the product we want to retrieve. We're using the Array.find() **method to find the product with the specified ID in the products array. If the product is not found, we're returning a 404 error with a message. Otherwise, we're returning the product in the response.
Update (PUT)
To update a product in the database, we'll create a new route using the app.put() method. This method creates a new route for PUT requests.
app.put('/products/:id', (req, res) => {
const { id } = req.params;
const { name, price } = req.body;
const productIndex = products.findIndex(p => p.id === parseInt(id));
if (productIndex === -1) {
return res.status(404).json({ message: 'Product not found' });
}
const updatedProduct = { id: parseInt(id), name, price };
products[productIndex] = updatedProduct;
res.json(updatedProduct);
});
In this example, we're creating a new route for the /products/:id endpoint, where :id is a parameter that represents the ID of the product we want to update. We're using the req.body object to extract the name and price of the updated product. We're then using the** Array.findIndex()** method to find the index of the product with the specified ID in the products array. If the product is not found, we're returning a 404 error with a message. Otherwise, we're updating the product in the array and returning the updated product in the response.
Delete (DELETE)
To delete a product from the database, we'll create a new route using the app.delete() method. This method creates a new route for DELETE requests.
app.delete('/products/:id', (req, res) => {
const { id } = req.params;
const productIndex = products.findIndex(p => p.id === parseInt(id));
if (productIndex === -1) {
return res.status(404).json({ message: 'Product not found' });
}
const deletedProduct = products.splice(productIndex, 1)[0];
res.json(deletedProduct);
});
In this example, we're creating a new route for the** /products/:id** endpoint, where : id is a parameter that represents the ID of the product we want to delete. We're using the** Array.findIndex()** method to find the index of the product with the specified ID in the products array. If the product is not found, we're returning a 404 error with a message. Otherwise, we're deleting the product from the array using the **Array.splice() **method and returning the deleted product in the response.
Conclusion
In this blog post, we've learned how to perform Update and Delete operations using Express.js with a simple example of code. By combining these operations with the Create and Read operations we learned in the previous post, we can create a fully functional CRUD API using Express.js.
Top comments (0)