my code below returns "User deleted" even if the user was already deleted. I'd prefer to throw a 404 in this case, but I'd like to query the DB as less as possible.
Is there a way to get the userNotFound
(see below) without manually checking if the user existed before deletion? Maybe I missed a feature of remove()
or an alternative function.
var itemId = 123;
Item.remove({id: itemId}, function(err) {
if (err) {
return res.json({success: false, msg: 'Cannot remove item'});
}
// !!!
if (userNotFound) {
return res.status(404).json({success: false, msg: 'User not found'});
}
// /!!!
res.json({success: true, msg: 'User deleted.'});
});
Thanks in advance!
There is currently no method called deleteById() in mongoose. However, there is the deleteOne() method with takes a parameter, filter , which indicates which document to delete. Simply pass the _id as the filter and the document will be deleted.
Mongoose | deleteOne() Function The deleteOne() function is used to delete the first document that matches the conditions from the collection. It behaves like the remove() function but deletes at most one document regardless of the single option.
We can delete documents using mongoose with the help of different methods like Model. deleteOne(), Model. findOneAndDelete(), Model. deleteMany(), and Model.
The mongoose. model() function of the mongoose module is used to create a collection of a particular database of MongoDB. The name of the collection created by the model function is always in plural format mean GFG to gfss and the created collection imposed a definite structure.
The problem with the above approach is that userNotFound
will always be undefined
since you haven't defined it in the callback arguments. Better to use the findOneAndRemove()
function so that you can return the document removed if found:
var itemId = 123;
Item.findOneAndRemove({ id: itemId })
.exec(function(err, item) {
if (err) {
return res.json({success: false, msg: 'Cannot remove item'});
}
if (!item) {
return res.status(404).json({success: false, msg: 'User not found'});
}
res.json({success: true, msg: 'User deleted.'});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With