If you have any query feel free to chat us!
Happy Coding! Happy Learning!
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.
Comments: 2
I am not able to access videos from second class and further. I have already completed first class
When will I get my course?
Now, Your query was resolved.