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

Comments: 2

profile
@niteshguptav63
17-Nov-2024, 01:39 PM

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

profile
@niteshguptav63
16-Nov-2024, 10:56 AM

When will I get my course?

profile
@admin79
17-Nov-2024, 01:29 PM

Now, Your query was resolved.

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?