153

How can I know the count of a model that data has been saved? there is a method of Model.count(), but it doesn't seem to work.

var db = mongoose.connect('mongodb://localhost/myApp');
var userSchema = new Schema({name:String,password:String});
userModel =db.model('UserList',userSchema);        
var userCount = userModel.count('name');

userCount is an Object, which method called can get a real count?

Thanks

1
  • 1
    If you're using ES 2016, you can wrap the call to count inside of a promise and call it with a generator.
    – mikeyGlitz
    Apr 17, 2016 at 1:54

9 Answers 9

174

The reason your code doesn't work is because the count function is asynchronous, it doesn't synchronously return a value.

Here's an example of usage:

userModel.count({}, function( err, count){
    console.log( "Number of users:", count );
})
4
  • Give me example to get count synchronous way of method Sep 11, 2017 at 10:41
  • Same for me. I am looking for the same
    – nowox
    May 21, 2018 at 11:40
  • 21
    count method is depricated, you can use countDocuments same syntax
    – Kir Novak
    Jul 10, 2018 at 0:52
  • @KirNovak Thanks bro. I also provided the url in mongoose for the deprecation.
    – Tes3awy
    Aug 12, 2018 at 12:48
167

The code below works. Note the use of countDocuments.

 var mongoose = require('mongoose');
 var db = mongoose.connect('mongodb://localhost/myApp');
 var userSchema = new mongoose.Schema({name:String,password:String});
 var userModel =db.model('userlists',userSchema);
 var anand = new userModel({ name: 'anand', password: 'abcd'});
 anand.save(function (err, docs) {
   if (err) {
       console.log('Error');
   } else {
       userModel.countDocuments({name: 'anand'}, function(err, c) {
           console.log('Count is ' + c);
      });
   }
 }); 
0
51

You should give an object as argument

userModel.countDocuments({name: "sam"});

or

userModel.countDocuments({name: "sam"}).exec(); //if you are using promise

or

userModel.countDocuments({}); // if you want to get all counts irrespective of the fields

For the older versions of mongoose, use

userModel.count({name: "sam"});
2
  • 4
    DeprecationWarning: collection.count is deprecated, you should use .estimatedDocumentCount() or .countDocuments() instead.
    – HMagdy
    Jul 23, 2019 at 19:02
  • 1
    countDocuments is the right one according to the docs from mongoose ;), thanks Jun 3, 2021 at 0:01
33

The collection.count is deprecated, and will be removed in a future version. Use collection.countDocuments or collection.estimatedDocumentCount instead.

userModel.countDocuments(query).exec((err, count) => {
    if (err) {
        res.send(err);
        return;
    }

    res.json({ count: count });
});
4
  • 3
    here is the documentation link : mongoosejs.com/docs/api.html#model_Model.estimatedDocumentCount
    – babar78
    Sep 11, 2018 at 10:45
  • I had the problem, that in our project a setup routine tests for existing items in any collections. The count() method behaved strange: when the collection was not empty, it sometimes returned nothing (undefined, null, zero or false - we could not investigate it further). We still did not find out what caused the problem since it was a race condition that happend very seldomly. Using countDocuments({}) now works for us. Thank you! Oct 25, 2018 at 14:48
  • UnhandledPromiseRejectionWarning: TypeError: userModel.countDocuments is not a function I get an error when using it on my own userModel?
    – Luke Brown
    Apr 2, 2019 at 15:53
  • How can we make "userModel.countDocuments" as synchronous call so that I can add a virtual to the schema that adds some "key & value" in my document.
    – Satyam
    Jul 27, 2019 at 5:49
24

Background for the solution

As stated in the mongoose documentation and in the answer by Benjamin, the method Model.count() is deprecated. Instead of using count(), the alternatives are the following:

Model.countDocuments(filterObject, callback)

Counts how many documents match the filter in a collection. Passing an empty object {} as filter executes a full collection scan. If the collection is large, the following method might be used.

Model.estimatedDocumentCount()

This model method estimates the number of documents in the MongoDB collection. This method is faster than the previous countDocuments(), because it uses collection metadata instead of going through the entire collection. However, as the method name suggests, and depending on db configuration, the result is an estimate as the metadata might not reflect the actual count of documents in a collection at the method execution moment.

Both methods return a mongoose query object, which can be executed in one of the following two ways. Use .exec() if you want to execute a query at a later time.

The solution

Option 1: Pass a callback function

For example, count all documents in a collection using .countDocuments():

someModel.countDocuments({}, function(err, docCount) {
    if (err) { return handleError(err) } //handle possible errors
    console.log(docCount)
    //and do some other fancy stuff
})

Or, count all documents in a collection having a certain name using .countDocuments():

someModel.countDocuments({ name: 'Snow' }, function(err, docCount) {
    //see other example
}

Option 2: Use .then()

A mongoose query has .then() so it’s “thenable”. This is for a convenience and query itself is not a promise.

For example, count all documents in a collection using .estimatedDocumentCount():

someModel
    .estimatedDocumentCount()
    .then(docCount => {
        console.log(docCount)
        //and do one super neat trick
    })
    .catch(err => {
        //handle possible errors
    })

Option 3: Use async/await

When using async/await approach, the recommended way is to use it with .exec() as it provides better stack traces.

const docCount = await someModel.countDocuments({}).exec();

Learning by stackoverflowing,

1
  • 2
    Awesome answer!
    – Mayinx
    Nov 5, 2021 at 11:15
9

Using mongoose.js you can count documents,

  • count all
const count = await Schema.countDocuments();
  • count specific
const count = await Schema.countDocuments({ key: value });
4

The highest voted answers here are perfectly fine I just want to add up the use of await so that the functionality asked for can be achieved:

const documentCount = await userModel.count({});
console.log( "Number of users:", documentCount );

It's recommended to use countDocuments() over 'count()' as it will be deprecated going on. So, for now, the perfect code would be:

const documentCount = await userModel.countDocuments({});
console.log( "Number of users:", documentCount );
4

Model.count() method is deprecated in mongoose version 6.2.0. If you want to count the number of documents in a collection, e.g. count({}), use the estimatedDocumentCount() function instead. Otherwise, use the countDocuments() function instead.

Model.estimatedDocumentCount() Estimates the number of documents in the MongoDB collection. It is Faster than using countDocuments() for large collections because estimatedDocumentCount() uses collection metadata rather than scanning the entire collection.

Example:

const numAdventures = await Adventure.estimatedDocumentCount();

reference : https://mongoosejs.com/docs/api.html#model_Model.estimatedDocumentCount

-1

As said before, your code will not work the way it is. A solution to that would be using a callback function, but if you think it would carry you to a 'Callback hell', you can search for "Promisses".

A possible solution using a callback function:

//DECLARE  numberofDocs OUT OF FUNCTIONS
     var  numberofDocs;
     userModel.count({}, setNumberofDocuments); //this search all DOcuments in a Collection

if you want to search the number of documents based on a query, you can do this:

 userModel.count({yourQueryGoesHere}, setNumberofDocuments);

setNumberofDocuments is a separeted function :

var setNumberofDocuments = function(err, count){ 
        if(err) return handleError(err);

        numberofDocs = count;

      };

Now you can get the number of Documents anywhere with a getFunction:

     function getNumberofDocs(){
           return numberofDocs;
        }
 var number = getNumberofDocs();

In addition , you use this asynchronous function inside a synchronous one by using a callback, example:

function calculateNumberOfDoc(someParameter, setNumberofDocuments){

       userModel.count({}, setNumberofDocuments); //this search all DOcuments in a Collection

       setNumberofDocuments(true);


} 
1
  • In function calculateNumberOfDoc(), why are you calling setNumberofDocuments(true) ? Would it not result in error first, even before the actual count is returned??
    – pravin
    Jan 24, 2015 at 10:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.