简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM