Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and Count elements of collection with Mongoose

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?

like image 210
Marc Bacvanski Avatar asked Feb 16 '16 21:02

Marc Bacvanski


People also ask

How do you count in Mongoose?

Mongoose | countDocuments() Function The countDocuments() function is used to count the number of documents that match the filter in a database collection.

What is the __ V field in Mongoose?

In Mongoose the “_v” field is the versionKey is a property set on each document when first created by Mongoose. This is a document inserted through the mongo shell in a collection and this key-value contains the internal revision of the document.24-Jun-2021.

What does model find () return in Mongoose?

The Model. find() function returns an instance of Mongoose's Query class. The Query class represents a raw CRUD operation that you may send to MongoDB. It provides a chainable interface for building up more sophisticated queries.

Can you define methods in a Mongoose schema?

Each Schema can define instance and static methods for its model.


1 Answers

You can use the length of the returned array:

Model.find().exec(function (err, results) {
  var count = results.length

});
like image 109
Gergo Avatar answered Oct 22 '22 16:10

Gergo