user4296898
user4296898

Reputation:

Check if MongoDb database is empty via db.collection.count() - doesn't work

I connect to MongoDb via Mongoose. Then, when connection is successful, I want to check whether the database is empty (meaning having no collections). If empty, I will seed the database with data.

I am using db.collection.count() to count collections but this code doesn't work.

var dbURI = 'mongodb://localhost/voddb';
mongoose.connect(dbURI);

mongoose.connection.on('connected', function () {  
    console.log('Mongoose default connection open to ' + dbURI);
    if(mongoose.connection.db.collection.count() == 0) {
        //seed database
    }  
});

It throws me an error at collection.count():

TypeError: Cannot read property 'collection' of undefined

What is wrong?

Upvotes: 2

Views: 12107

Answers (1)

Jitendra Khatri
Jitendra Khatri

Reputation: 774

You are using mongoose.connection.db.collection which is a function, You can use mongoose.connection.db.collection('your_collection_name').count()

Example :

var dbURI = 'mongodb://localhost/my_db_name';

mongoose.connect(dbURI);

mongoose.connection.on('connected', function () { 
console.log('Mongoose default connection open to ' + dbURI);

// To List all Collections of a Database
mongoose.connection.db.listCollections().toArray(function(err, names) {
    if (err) {
        console.log(err);
    }
    else {
        names.forEach(function(e,i,a) {
            console.log("----->", e.name);
        });
    }
});

// To Count Documents of a particular collection
mongoose.connection.db.collection('users').count(function(err, count) {
    console.dir(err);
    console.dir(count);

    if( count == 0) {
        console.log("No Found Records.");
    }
    else {
        console.log("Found Records : " + count);
    }
});
});

Upvotes: 5

Related Questions