How to get all count of mongoose model?

smilexu picture smilexu · May 30, 2012 · Viewed 189.6k times · Source

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?

Thanks

Answer

UpTheCreek picture UpTheCreek · Mar 26, 2013

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 );
})