,

Express.js Tutorial: CRUD Part 2 – Update and Delete

Posted by






Express JS Tutorial – CRUD Part 2

Express JS Tutorial – CRUD Part 2

In this tutorial, we will continue with the CRUD operations in Express JS. In our previous tutorial, we covered the Create and Read operations. This time, we will focus on the Update and Delete operations.

UPDATE Operation

To update an existing record in the database, we need to use the HTTP method PUT. We can create a route in our Express application to handle the update operation.

      
app.put('/products/:id', (req, res) => {
  // retrieve the product id from the request parameters
  const productId = req.params.id;
  // retrieve the updated product details from the request body
  const updatedProduct = req.body;
  // update the product in the database
  // ...
  // send a response back to the client
  res.send('Product updated successfully');
});
      
    

With the above code, we can handle the update operation for a specific product in our database.

DELETE Operation

To delete a record from the database, we use the HTTP method DELETE. We can create a route in our Express application to handle the delete operation.

      
app.delete('/products/:id', (req, res) => {
  // retrieve the product id from the request parameters
  const productId = req.params.id;
  // delete the product from the database
  // ...
  // send a response back to the client
  res.send('Product deleted successfully');
});
      
    

With the above code, we can handle the delete operation for a specific product in our database.

By implementing the Update and Delete operations, we have completed the CRUD functionality in our Express application. It is essential to handle these operations carefully to avoid any unintended changes to the data in the database.

With this knowledge, you can now build more robust and dynamic web applications using Express JS. Stay tuned for more tutorials on Express JS and other web development technologies!