smilexu smilexu - 1 month ago 11
Node.js Question

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
?

Thanks

Answer

The code below works. Note the use of count.

 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'});
 anand.save(function (err, docs) {
   if (err) {
       console.log('Error');
   } else {
       userModel.count({name: 'anand'}, function(err, c) {
           console.log('Count is ' + c);
      });
   }
 });