Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

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

1 Answer

0 votes
by (107k points)

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

 anand.save(function (err, docs) {

   if (err) {

       console.log('Error');

   } else {

       userModel.countDocuments({name: 'anand'}, function(err, c) {

           console.log('Count is ' + c);

      });

   }

 }); 

Related questions

0 votes
1 answer
0 votes
1 answer
asked Feb 15, 2020 in Web Technology by ashely (50.2k points)
0 votes
2 answers
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...