Sonson123
Sonson123

Reputation: 11437

Mongoose: Count removed documents

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.

Upvotes: 12

Views: 9129

Answers (3)

Erich Haberman
Erich Haberman

Reputation: 1

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.

Upvotes: 0

AjayK
AjayK

Reputation: 443

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.");
        });

Upvotes: 2

JohnnyHK
JohnnyHK

Reputation: 311895

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."));
}

Upvotes: 31

Related Questions