Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number of documents using Mongoose?

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.

like image 440
kaizer Avatar asked Sep 11 '25 05:09

kaizer


2 Answers

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 
 
        });
    });
});
like image 167
chridam Avatar answered Sep 12 '25 21:09

chridam


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

const number = await Model.countDocuments();
console.log(number);
like image 25
Vasyl Boroviak Avatar answered Sep 12 '25 19:09

Vasyl Boroviak