25

I'm working on a Nodejs/Express/Mongoose app, and I wanted to implement an autoincrement ID features by incrementing the number of recorded documents, but I'm not able to get this count, cause Mongoose 'count' method doesn't return the number:

var number = Model.count({}, function(count){ return count;});

Is someone managed to get the count ? Help please.

Vasyl Boroviak
  • 5,959
  • 5
  • 51
  • 70
kaizer
  • 490
  • 1
  • 6
  • 17

6 Answers6

49

The count function is asynchronous, it doesn't synchronously return a value. Example usage:

Model.count({}, function(err, count){
    console.log( "Number of docs: ", count );
});

You can also try chaining it after a find():

Model.find().count(function(err, count){
    console.log("Number of docs: ", count );
});

UPDATE (node:25093 - DeprecationWarning):

using count is deprecated and you can also use "Collection.countDocuments" or "Collection.estimatedDocumentCount" exactly the way you used "count".

UPDATE:

As suggested by @Creynders, if you are trying to implement an auto incremental value then it would be worth looking at the mongoose-auto-increment plugin:

Example usage:

var Book = connection.model('Book', bookSchema);
Book.nextCount(function(err, count) {
 
    // count === 0 -> true 
 
    var book = new Book();
    book.save(function(err) {
 
        // book._id === 0 -> true 
 
        book.nextCount(function(err, count) {
 
            // count === 1 -> true 
 
        });
    });
});
chridam
  • 100,957
  • 23
  • 236
  • 235
  • It works that way, but I wanted to get the count back within a variable so that I can increment that variable: – kaizer Apr 09 '15 at 07:59
  • @kaizer Understand that the count function is asynchronous and can finish at any time so the variable `number` will be undefined when you're accessing it. You can only use the values inside the `count` function's callback. – chridam Apr 09 '15 at 08:05
  • 1
    @kaizer It seems you're trying to implement an auto incremental value? You can use the [mongoose-auto-increment](https://www.npmjs.com/package/mongoose-auto-increment) plugin for this. – Creynders Apr 09 '15 at 10:14
  • @Creynders you've got it man, thx, I'll try it and let you know – kaizer Apr 09 '15 at 11:05
18

If you are using node.js >= 8.0 and Mongoose >= 4.0 you should use await.

const number = await Model.countDocuments();
console.log(number);
Vasyl Boroviak
  • 5,959
  • 5
  • 51
  • 70
15

If anyone's checkin this out in 2019, count is deprecated. Instead, use countDocuments.

Example:

const count = await Model.countDocuments({ filterVar: parameter }); console.log(count);

Len Joseph
  • 1,406
  • 10
  • 21
3

If your collection is large - use Model.estimatedDocumentCount(). It's faster then count and countDocuments, because it doesn't scan the entire collection.

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

m02ph3u5
  • 3,022
  • 7
  • 38
  • 51
Art
  • 35
  • 4
0

It looks like you are expecting var number to contain the count value. In your callback function you are returning count but this is executed asynchronously so will not assign the value to anything.

Also, your first parameter in your callback function should be err.

For example:

var number = Model.count({}, function(err, count) {
    console.log(count); // this will print the count to console
});

console.log(number); // This will NOT print the count to console
JoGoFo
  • 1,928
  • 14
  • 31
-1

you hava to wait the callback function

Model.count({}, function(err , count){
  var number = count;
  console.log(number);
});

in JavaScript

setTimeout(function() {
  console.log('a');
}, 0);

console.log("b");

the "b" will be printed before "a" because

console.log('a')
hussam
  • 596
  • 5
  • 12