Create an Express route to handle deletion of documents from a MongoDB collection.
Create an Express route to handle deletion of documents from a MongoDB collection.
24226-Jul-2023
Updated on 27-Jul-2023
Home / DeveloperSection / Forums / Create an Express route to handle deletion of documents from a MongoDB collection.
Create an Express route to handle deletion of documents from a MongoDB collection.
Aryan Kumar
27-Jul-2023Sure, here is an Express route to handle deletion of documents from a MongoDB collection:
JavaScript
This route first imports the
express
andmongodb
modules. It then defines the MongoDB connection URL, which ismongodb://localhost:27017/mydb
.Next, the route defines a
get
handler for the/delete
route. The handler takes areq
andres
object as its input. Thereq
object contains the query parameters from the request, and theres
object is used to send the response back to the client.The
get
handler first connects to the MongoDB database and gets thepeople
collection. The handler then gets theid
of the document to be deleted from thereq
object.The handler then uses the
deleteOne()
method to delete the document from the collection. ThedeleteOne()
method returns a result object, which contains the number of documents that were deleted.If the document was deleted successfully, the handler sends a
200 OK
response back to the client. Otherwise, the handler sends a404 Not Found
response back to the client.To run this route, you can save it as a file called
delete.js
and then run it from the command line:This will start the Express server on port 3000. You can then test the route by making a GET request to
http://localhost:3000/delete?id=1
. If the document with the ID 1 exists in thepeople
collection, it will be deleted. Otherwise, a404 Not Found
response will be returned.