Deleting From DB

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 279:- Deleting From DB

To delete data from a MongoDB database using MongooseJS, we can use the deleteOne method provided by the model. The deleteOne method deletes the first document that matches the specified condition.

Here's an example of deleting a contact with the given id using the deleteOne method:

javascriptCopy code

const Contact = require('../models/contact'); // DELETE /contacts/:id app.delete('/contacts/:id', (req, res) => {  const id = req.params.id;  Contact.deleteOne({ _id: id }, (err, result) => {    if (err) {      console.error(err);      res.sendStatus(500);      return;    }    if (result.deletedCount === 0) {      res.sendStatus(404);      return;    }    console.log(`Deleted contact with id ${id}`);    res.sendStatus(204);  }); });

In this example, we first get the id of the contact to be deleted from the URL parameters using req.params.id. We then call the deleteOne method on the Contact model, passing in an object with the _id field set to the id parameter.

The deleteOne method takes a callback function that is called when the deletion is complete. In the callback function, we check if there was an error using the err parameter. If there was an error, we log it to the console and send a 500 status code to the client.

If the deletion was successful, the result parameter will contain information about the deletion, including the number of documents deleted. If no documents were deleted, we send a 404 status code to the client.

Finally, if the deletion was successful and at least one document was deleted, we log a message to the console and send a 204 status code to the client, indicating that the request was successful but there is no response to send back.

31. My First Express App - Intro To Databases

2 Comments

@niteshguptav63
niteshguptav63 Nov 17, 2024 at 1:39 PM

I am not able to access videos from second class and further. I have already completed first class

@niteshguptav63
niteshguptav63 Nov 16, 2024 at 10:56 AM

When will I get my course?

@admin79
admin79 Nov 17, 2024 at 1:29 PM

Now, Your query was resolved.

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support