0

this is my code

var mongoose = require('mongoose');
db = mongoose.createConnection('mongodb://localhost/myDB');

there is collection users in myDB, how can i get number of documents in users?

epsilon
  • 868
  • 2
  • 8
  • 17

2 Answers2

0

Have you even tried to do this yourself?

None the less,

db.open (function(error){
    db.collection("users", function(error, collection){
        collection.count({}, function(error, numOfDocs) {
            console.log(numOfDocs + ' total users');
        });
    });
});

That should get you started, I ahven't tested this code but I remember doing it like that.

Tachyon
  • 2,171
  • 3
  • 22
  • 46
  • i have tried, and i don't understand your code, but it works. Can you leave a link to docs about the `count` ? – epsilon Jan 23 '18 at 11:28
  • Sure, here we go, [Mongoose](http://mongoosejs.com/docs/api.html#model_Model.count) and [MongoDB](https://docs.mongodb.com/manual/reference/method/db.collection.count/) Just to explain the code for you, db.open opens the connection to your MongoDB database. db.collection('Users'...) will select the users collection, and will return the collection in the collection variable when found. collection.count, uses that returned collection to count the number of documents, and then returns it in numOfDocs. – Tachyon Jan 23 '18 at 11:31
  • but why i should write exactly that? is this the only way? if i want to get just number, should i write this huge code? – epsilon Jan 23 '18 at 11:37
  • @epsilon Because you have to instruct your computer what to look for. You could look at tools to manage your database, it could make querying a little bit easier perhaps. – Kyle van Til Jan 23 '18 at 12:33
0

try this way, its a snippet from my dummy code and it should work

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/myDB');   // Connect to mongodb
mongoose.connection.once('open',(db)=>{         // opens the connection for us
    console.log("Connection made to mongodb");
    mongoose.model('<collection>').count().then((count) => { // replace <collection> with collection name
            console.log(count);
    })
}).on('error',(error)=>{
    console.log("connection error to mongodb : " + error);
}); 
Jithin Scaria
  • 1,271
  • 1
  • 15
  • 26