Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 824
Sonson123 Avatar asked Aug 17 '12 13:08

Sonson123


People also ask

How do you count in Mongoose?

Mongoose | countDocuments() Function The countDocuments() function is used to count the number of documents that match the filter in a database collection.

What is remove in Mongoose?

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.

What is skip in Mongoose?

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.

Is Mongoose better than MongoDB?

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.


2 Answers

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."));
}
like image 62
JohnnyHK Avatar answered Oct 15 '22 00:10

JohnnyHK


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.");
        });
like image 29
AjayK Avatar answered Oct 15 '22 00:10

AjayK