Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

db.collectionNames doesn't work in Node.js

I want to check if a collection exist in Node.js. I use the db.collectionNames to get the names list in the db but nothing happened. The code:

connectDB(DBURL).then(function(db) {
        console.log('db connect ok');

        db.collectionNames('test', function(err, collectionNames) {
            console.log('get collection names');

            if(err) console.log(err);
            else console.log(collectionNames);
        });

    }, function(err) {
        console.log(err);
    });

The connectDB(DBURL) is a promise object, it works perfectly. The output:

app-0 try to connect db
app-0 db connect ok

You can see there's nothing output from the function in collectionNames. I have no idea why.

I can get the collections name in Mongo shell by db.getCollectionNames:

> db.getCollectionNames()
[ "system.indexes", "test" ]
like image 971
Brick Yang Avatar asked Oct 19 '15 12:10

Brick Yang


1 Answers

Are you using >2.0 version of the driver?

If so, you will need to use listCollections instead - this is one of the changes in the update from 1.x

Something like:

db.listCollections().toArray(function(err, collections){
    //collections = [{"name": "coll1"}, {"name": "coll2"}]
});
like image 144
Adam Comerford Avatar answered Sep 30 '22 13:09

Adam Comerford