How can I count the number of all documents in a Collection using Mongoose?

9,553 views
Skip to first unread message

dessa beca GP

unread,
Jul 16, 2014, 11:40:54 AM7/16/14
to mongoo...@googlegroups.com
I am trying to count all Documents in a Collection but I just get 'undefined '. 

I searched in  Mongoose Documentation but the only example that I have is this :

 users.count(query , function(err, result){
     
if(err) ...
// count is the result
 
var count = result
     
});


 So, in Mongoose Documentation I can count the number of documents that match a query passed in the function, but

How can I count all the Documents in a Collection? All without any query? 

In Mongoose terminal I can just do :

db.CollectionName.count()


Does someone know how to do it using Mongoose? 

Thank you.

James Irwin

unread,
Dec 27, 2014, 11:38:41 AM12/27/14
to mongoo...@googlegroups.com
if you want to count a all users in users try
users.count({}, function(err, result){
});
or you can chain it after a find
users.find().count(function(err, count){
});

Petr Vocelka

unread,
Oct 1, 2016, 7:48:44 PM10/1/16
to Mongoose Node.JS ODM
I know it's too late, but at least I can provide helpful answer...

We can take advantage of Mongoose "Driver Access" to solve this problem, so the final result might look like this:

Koa
return users.collection.count();

Express
users.collection.count().exec(function(err, result) {
    if(err) ...
});

Reply all
Reply to author
Forward
0 new messages