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" ]
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"}]
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With