How to get all count of mongoose model?


How can I know the count of a model that data has been saved? there is a method of Model.count(), but it doesn't seem to work.

var db = mongoose.connect('mongodb://localhost/myApp');
var userSchema = new Schema({name:String,password:String});
userModel =db.model('UserList',userSchema);        
var userCount = userModel.count('name');

userCount is an Object, which method called can get a real count?


10/25/2016 6:36:49 AM

Accepted Answer

The code below works. Note the use of countDocuments.

 var mongoose = require('mongoose');
 var db = mongoose.connect('mongodb://localhost/myApp');
 var userSchema = new mongoose.Schema({name:String,password:String});
 var userModel =db.model('userlists',userSchema);
 var anand = new userModel({ name: 'anand', password: 'abcd'}); (err, docs) {
   if (err) {
   } else {
       userModel.countDocuments({name: 'anand'}, function(err, c) {
           console.log('Count is ' + c);
8/23/2019 3:27:18 PM

The reason your code doesn't work is because the count function is asynchronous, it doesn't synchronously return a value.

Here's an example of usage:

userModel.count({}, function( err, count){
    console.log( "Number of users:", count );

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow