Open In App

Mongoose count() Function

Improve
Improve
Like Article
Like
Save
Share
Report

The Query.prototype.count() function is used to count the number of documents in a collection. This functions basically specifies this query as a count query.

Syntax: 

Query.prototype.count()

Parameters: This function accepts one array parameter i.e. callback function.
 

Return Value: This function returns Query Object.
 

Installation of mongoose module: 

npm install mongoose
  • After installing the mongoose module, you can check your mongoose version in command prompt using the command. 
npm version mongoose
  • After that, you can just create a folder and add a file for example, index.js as shown below.

Database: The sample database used here is shown below: 
 

Example 1: Filename: index.js 
 

javascript




const mongoose = require('mongoose');
  
// Database connection
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});
  
// User model
const User = mongoose.model('User', { 
    name: { type: String },
    age: { type: Number }
});
  
var query = User.find();
query.count(function (err, count) {
    if (err) console.log(err)
    else console.log("Count is", count)
});


Steps to run the program: 

  • The project structure will look like this: 

  • Run index.js file using below command: 
node index.js

Output: 

Count is 4

Example 2: Filename: index.js 
 

javascript




const express = require('express');
const mongoose = require('mongoose');
const app = express()
  
// Database connection
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});
  
// User model
const User = mongoose.model('User', { 
    name: { type: String },
    age: { type: Number }
});
  
var query = User.find();
query.count(function (err, count) {
    if (err) console.log(err)
    else console.log("Count:", count)
});
  
app.listen(3000, function(error ) {
    if(error) console.log(error)
    console.log("Server listening on PORT 3000")
});


Steps to run the program: 

  • The project structure will look like this: 

  • Run index.js file using below command: 
node index.js

Output: 

Server listening on PORT 3000
Count: 4

Reference: https://mongoosejs.com/docs/api/query.html#query_Query-count



Last Updated : 10 Sep, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads