How to get number of documents using Mongoose?
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
});
});
});
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);
If you are using node.js >= 8.0 and Mongoose >= 4.0 you should use await
.
const number = await Model.countDocuments();
console.log(number);