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:

  1. Install the MongoDB Node.js driver by running the following command in your project directory: npm install mongodb

  2. Import the MongoDB Node.js driver in your code: javascript const { MongoClient } = require("mongodb");

  3. 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 });

  4. Perform the delete operation using the deleteOne or deleteMany method on the collection you want to delete from. For example, to delete a single document with a specific condition, you can use deleteOne: 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.

  1. If the deletedCount property of the result object is 1, it means the record was successfully deleted. Otherwise, if it is 0, 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.