0

im using mongoclient and im sure that I have connection to the database

const client = new MongoClient(uri);
const datatbaseslist = client.db().admin().listDatabases();
    datatbaseslist.databases.forEach(db => {
        console.log($db.name)
    });

I saw that code in a video of the mongodb and its not working. thanks

I have tried looking for other versions to that line

const datatbaseslist = client.db().admin().listDatabases();
    datatbaseslist.databases.forEach(db => {
        console.log($db.name)
    });

because im pretty sure that the problem is there.

3
  • Try client.db.admin().listDatabases() or db.adminCommand( { listDatabases: 1 } ) See stackoverflow.com/questions/39748101/… Commented Dec 5, 2022 at 14:45
  • 1
    listDatabases() returns a Promise, so you should either await it or pipe to .then() Commented Dec 5, 2022 at 14:48
  • You are using db in the function parameter but you're using $db in the console log. Also, it'd help if you share the error you're getting Commented Dec 5, 2022 at 15:45

1 Answer 1

1

I think your question title is saying one thing (collections) and your code is confusing this any another (databases).

  • A mongodb server can have multiple databases.
  • A database can have multiple collections.
  • You connect to the server using a client.
  • Normally if you want to know about the databases, you would use admin(). Or to connect to a specific database (although you can connect via URI), the you use db(dbName) from the client.
  • Once you have a db object, you can get the collections from there.

The below code shows you how to get both databases and collections.

const { MongoClient } = require('mongodb')

async function main () {
  // Set config
  const uri = 'mongodb://localhost:27017'
  const client = new MongoClient(uri)

  try {
    // Connect to the MongoDB cluster
    await client.connect()

    // Get databases
    const databasesList = await client.db().admin().listDatabases()
    for (const dbName of databasesList.databases.map(db => db.name)) {
      console.log('DB:         ', dbName)

      // Get collections for each database
      const collections = await client.db(dbName).listCollections().toArray()
      console.log('Collections:', collections.map(col => col.name).join(', '))
      console.log('---------------------------------------------')
    }
  } catch (e) {
    // Handle any erros
    console.error(e)
  } finally {
    // Always close the connection to the database when finished
    await client.close()
  }
}

main().catch(console.error)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.