0
votes

I'm trying to get all collection names in mongodb (v4.0.2) and using [email protected] nodejs driver. From the docs, I can see that listCollections might work, but running the following:

const Db = require('mongodb').Db
const Server = require('mongodb').Server
const db = new Db(dbName, new Server(host, port, options), {})
db.listCollections().toArray((error, collectionNames) => {
  console.error(error)
  console.log(JSON.stringify(collectionNames))
})

… leads to this error:

if (this.serverConfig.capabilities().hasListCollectionsCommand) {
TypeError: Cannot read property 'hasListCollectionsCommand' of null
   at Db.listCollections ({path}/node_modules/mongodb/lib/db.js:493:39)
   at db.createCollection ({path}/sampleMongoDB.js:19:8)
   at err ({path}/node_modules/mongodb/lib/utils.js:415:14)
   at executeCallback ({path}/node_modules/mongodb/lib/utils.js:404:25)
   at executeOperation ({path}/node_modules/mongodb/lib/utils.js:422:7)
   at Db. ({path}/node_modules/mongodb/lib/db.js:431:12)
   at Db.deprecated [as createCollection] ({path}/node_modules/mongodb /lib/utils.js:661:17)
   at Object.< anonymous > ({path}/sampleMongoDB.js:18:6)
   at Module._compile (module.js:653:30)
   at Object.Module._extensions..js (module.js:664:10)

My questions are:

  1. Is there a docs site for MongoDB NodeJs drivers where we can refer examples from?
  2. If not, what's the correct way to query?
1

1 Answers

0
votes

I was able to work it out. The MongoClient's instance returns a db instance, which inturn helps run mongodb.Db methods.

Here's a sample code that worked (Ref. to MongoDB guides)

const options = {
  useNewUrlParser: true, // Add this, if you wish to avoid {https://stackguides.com/questions/50448272/avoid-current-url-string-parser-is-deprecated-warning-by-setting-usenewurlpars} issue
}

const client = new MongoClient(connectionUri, options)

return client.connect().then(() => {
  const db = client.db(dbName)
  return db.listCollections()
    .toArray()
    .then((collections) => {
      // Collections array
    })

})

@Community mods - if required, kindly close this question.