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.
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 you are using node.js >= 8.0 and Mongoose >= 4.0 you should use await
.
const number = await Model.countDocuments();
console.log(number);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With