db.collectionNames在Node.js中不起作用

我想检查一下在Node.js中是否存在一个集合。 我使用db.collectionNames获取数据库中的名称列表,但没有发生任何事情。 代码:

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

connectDB(DBURL)是一个promise对象,它工作的很好。 输出:

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

你可以看到collectionNames的函数没有任何输出。 我不知道为什么。

我可以通过db.getCollectionNames在Mongo shell中获取集合名称:

 > db.getCollectionNames() [ "system.indexes", "test" ] 

您是否使用> 2.0版本的驱动程序?

如果是这样,您将需要使用listCollections代替 – 这是1.x更新中的一个变化

就像是:

 db.listCollections().toArray(function(err, collections){ //collections = [{"name": "coll1"}, {"name": "coll2"}] });