How can I check if the remove-method of a Mongoose model really has removed something?
MyModel.remove({_id: myId}, function(err, entry) {
if(entry == null) next(new Error("ID was not found.")); // this doesn't work
}
Can I check how many documents were removed?
In the Mongo-Documentation kristina1 write in a comment:
If you call db.runCommand({getLastError:1}) after a remove and the "n" field will tell you how many documents were deleted.
But I don't know how to do this with Mongoose.
Mongoose | countDocuments() Function The countDocuments() function is used to count the number of documents that match the filter in a database collection.
remove() is a Mongoose function that removes a given path or paths from a document. It removes the path based on the passed argument. A path is a field in a document present in a database or collection.
In Mongoose, the skip() method is used to specify the number of documents to skip. When a query is made and the query result is returned, the skip() method will skip the first n documents specified and return the remaining.
Mongoose allows users to conveniently create and manage data in MongoDB. While it is possible to manage data, define schemas, etc. using MongoDB APIs, it is quite difficult to do so. Hence, Mongoose has made lives easier.
Mongoose < 4, MongoDB < 3
The second parameter to the remove
callback is a number containing the number of documents removed.
MyModel.remove({_id: myId}, function(err, numberRemoved) {
if(numberRemoved === 0) next(new Error("ID was not found."));
}
Mongoose 4.x, MongoDB 3.x
The second parameter passed to the remove
callback is now an object with the result.n
field indicating the count of removed documents:
MyModel.remove({_id: myId}, function(err, obj) {
if(obj.result.n === 0) next(new Error("ID was not found."));
}
I tried this with latest version of mongoose, and it did not work. As the second parameter comes back as operation result, not just count. Used as below, it worked :
Model.remove({
myId: req.myId
}, function(err, removeResult) {
if (err) {
console.log(err);
}
if (removeResult.result.n == 0) {
console.log("Record not found");
}
Console.log("Deleted successfully.");
});
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