![]() |
VOOZH | about |
The Model.count() method of the Mongoose API is used to count the number of documents present in the collection based on the given filter condition. It returns the query object and count of documents present in the collection.
Syntax:
Model.count()Parameters: The Model.count() method accepts two parameters:
Return Value: The Model.count() function returns a query object and promise.
Setting up Node.js application:
Step 1: Create a Node.js application using the following command:
npm initStep 2: After creating the NodeJS application, Install the required module using the following command:
npm install mongooseProject Structure: The project structure will look like this:
Database Structure: The database structure will look like this, the following documents are present in the collection.
Example 1: In this example, We have established a database connection using mongoose and defined model over userSchema, having two columns or fields "name" and "age". In the end, we are using count() method on the User model which will count the number of documents present in the collection that matches the filter condition.
Step to run the program: To run the application execute the below command from the root directory of the project:
node app.jsOutput:
2Example 2: In this example, we are getting output as a query object that contains meta data information.
Step to run the program: To run the application execute the below command from the root directory of the project:
node app.jsOutput:
Reference: https://mongoosejs.com/docs/api/model.html#model_Model-count