In Mongoose, I need to find elements in a collection and count them, and getting both the results of the find and count. I have tried
Model.find().count(function (err, count) {
// Get count, but cannot get results of find
});
Is there a way to get both find() and count() without calling them twice?
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
});
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
})