how to check record successfully delete in mongodb node js
How to Check if a Record is Successfully Deleted in MongoDB using Node.js
To check if a record is successfully deleted in MongoDB using Node.js, you can follow these steps:
Install the MongoDB Node.js driver by running the following command in your project directory:
npm install mongodb
Import the MongoDB Node.js driver in your code:
javascript const { MongoClient } = require("mongodb");
Connect to the MongoDB database using the
MongoClient.connect
method:javascript MongoClient.connect("mongodb://localhost:27017", (err, client) => { if (err) throw err; const db = client.db("your_database_name"); // Perform delete operation here });
Perform the delete operation using the
deleteOne
ordeleteMany
method on the collection you want to delete from. For example, to delete a single document with a specific condition, you can usedeleteOne
:javascript db.collection("your_collection_name").deleteOne({ _id: ObjectId("your_document_id") }, (err, result) => { if (err) throw err; if (result.deletedCount === 1) { console.log("Record deleted successfully"); } else { console.log("Record not found"); } client.close(); });
In the above code, replace "your_database_name"
with the name of your MongoDB database, "your_collection_name"
with the name of your collection, and "your_document_id"
with the ID of the document you want to delete.
- If the
deletedCount
property of theresult
object is1
, it means the record was successfully deleted. Otherwise, if it is0
, it means the record was not found.
Here's a complete example that demonstrates the above steps:
const { MongoClient, ObjectId } = require("mongodb");
MongoClient.connect("mongodb://localhost:27017", (err, client) => {
if (err) throw err;
const db = client.db("your_database_name");
db.collection("your_collection_name").deleteOne({ _id: ObjectId("your_document_id") }, (err, result) => {
if (err) throw err;
if (result.deletedCount === 1) {
console.log("Record deleted successfully");
} else {
console.log("Record not found");
}
client.close();
});
});
Please note that you need to replace "your_database_name"
, "your_collection_name"
, and "your_document_id"
with the appropriate values for your MongoDB setup.
I hope this helps! Let me know if you have any further questions.