xxxxxxxxxx
// Delete a user by username
app.delete('/users/:Username', (req, res) => {
Users.findOneAndRemove({ Username: req.params.Username })
.then((user) => {
if (!user) {
res.status(400).send(req.params.Username + ' was not found');
} else {
res.status(200).send(req.params.Username + ' was deleted.');
}
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
});
xxxxxxxxxx
Campground.findByIdAndRemove(req.params.id, function(err){
if(err){
res.redirect("/campgrounds");
} else {
res.redirect("/campgrounds");
}
});
xxxxxxxxxx
// The "todo" in this callback function represents the document that was found.
// It allows you to pass a reference back to the client in case they need a reference for some reason.
Todo.findByIdAndRemove(req.params.todoId, (err, todo) => {
// As always, handle any potential errors:
if (err) return res.status(500).send(err);
// We'll create a simple object to send back with a message and the id of the document that was removed
// You can really do this however you want, though.
const response = {
message: "Todo successfully deleted",
id: todo._id
};
return res.status(200).send(response);
});
xxxxxxxxxx
Tank.deleteOne({ size: 'large' }, function (err) {
if (err) return handleError(err);
// deleted at most one tank document
});
xxxxxxxxxx
// Example: Delete a Single Document
// Delete a document that matches the specified condition.
User.findOneAndDelete({ name: 'Alice' }, (err, deletedUser) => {
// Handle error or use deletedUser
});
// Example: Delete Multiple Documents
// Delete all documents that match the specified condition.
User.deleteMany({ age: { $gte: 30 } }, (err, result) => {
// Handle error or use result
});
// Example: Delete by ID
// Delete a document by its unique identifier.
User.findByIdAndDelete('123abc', (err, deletedUser) => {
// Handle error or use deletedUser
});
// Example: Delete a Field from a Document
// Remove a specific field from a document.
User.updateOne({ name: 'Bob' }, { $unset: { location: 1 } }, (err, result) => {
// Handle error or use result
});
// Example: Delete an Element from an Array
// Remove a specific element from an array field in a document.
User.updateOne({ name: 'Charlie' }, { $pull: { skills: 'Node.js' } }, (err, result) => {
// Handle error or use result
});
xxxxxxxxxx
const removedItem = await Items.findOneAndRemove({ id: itemId })
xxxxxxxxxx
No,
You cannot undo a delete operation.
Once deleted the data cannot be retrieved UNLESS a dump of the collections is created
before deleting it.