Find and Count elements of collection with Mongoose
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:
SomeModel.countDocuments({}, function(err, count) {
if (err) { return handleError(err) } //handle possible errors
console.log(count)
//and do some other fancy stuff
})
or
SomeModel
.estimatedDocumentCount()
.then(count => {
console.log(count)
//and do one super neat trick
})
.catch(err => {
//handle possible errors
})
You can use the length of the returned array:
Model.find().exec(function (err, results) {
var count = results.length
});
You have to do 2 separate queries unfortunately. Festo's answer only works if you have less elements in the database than the limit.
var countQuery = Model.count();
var findQuery = Model.find().limit(2);
countQuery.exec(function (e, count) {
console.log('count', count); // can be more than 2, this is not calculated, mongo stores this value internally
})
findQuery.exec(function(e, data) {
console.log('found items', data); // will be 2 or less elements
});