Mongoose: Count removed documents

Viewed 8470

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.

3 Answers

I stumbled upon this in 2020 and found with Mongoose 5.9.28 that the result no longer requires a result wrapper, so using remove to get a count of deleted records in an async method looks like:

async function remove(query) {
  const result = await ItemModel.remove(query);
  return result.n;
}

Of course, collection.remove is deprecated in favor of deleteOne or deleteMany, so try this as well.

Related