,

Efficient Back-End Development using Node JS with Express JS: Utilizing the Delete API to Remove Data from MongoDB

Posted by








Back-End Development | Node JS with Express JS | Delete API

Back-End Development with Node JS and Express JS

Back-end development is an essential part of building web applications. It involves working on the server-side of the application, handling database interactions, and providing data to the front-end. Node JS and Express JS are popular frameworks for building back-end systems. In this article, we will focus on implementing a delete API in Node JS with Express JS to delete data from MongoDB.

Setting up the Back-End Environment

Before we start implementing the delete API, let’s set up our back-end environment. First, make sure you have Node JS and npm (Node Package Manager) installed on your system. Then, create a new Node JS project and install the necessary dependencies including Express JS and MongoDB driver.


npm init -y
npm install express mongodb

Creating the Delete API

Now that we have our environment set up, let’s create the delete API using Express JS. First, create a new file named app.js and import the required modules.


const express = require('express');
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
const ObjectId = mongodb.ObjectId;

const app = express();
const port = 3000;
const mongoURL = 'mongodb://localhost:27017';
const dbName = 'mydatabase';

app.delete('/api/delete/:id', async (req, res) => {
const id = req.params.id;
try {
const client = await MongoClient.connect(mongoURL);
const db = client.db(dbName);
const result = await db.collection('mycollection').deleteOne({ _id: new ObjectId(id) });
res.status(200).json({ message: 'Data deleted successfully' });
client.close();
} catch (error) {
res.status(500).json({ message: 'Error deleting data' });
}
});

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

Deleting Data from MongoDB

In the delete API, we use the app.delete() method to handle HTTP DELETE requests. We extract the id parameter from the request and use it to delete the corresponding data from MongoDB using the deleteOne() method.

Now, you can start the server and test the delete API using a tool like Postman. Make a DELETE request to http://localhost:3000/api/delete/your_data_id and check if the data is successfully deleted from the MongoDB collection.

Conclusion

In this article, we have demonstrated how to implement a delete API in Node JS with Express JS to delete data from MongoDB. Back-end development with Node JS and Express JS provides a powerful and flexible platform for building robust web applications with database interactions. Understanding how to create APIs to handle database operations is essential for any back-end developer.