Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get mongodb database base name after connection in nodejs?

Tags:

mongodb

I found that the latest version of MongoDB nodejs driver introduced MongoClient class which is the first class instance I can get after making a connection. But it doesn't provide a default database instance. Below is the source code.

MongoClient.connect(url, (err, client) => {
    if(err) {
      return null;
    }
    client.db('test');  // how can I know the database name? Do I need to parse the url?
  });

The above code shows how to get the mongo client instance after connection. I need to call client.db to get the database instance. My question is how I know the default database name in the client instance. All I get is the connection url. Do I need to parse the connection url in order to get the connected database which is test in the above example?

I know there is a method db.getName() returnes the database name. But how can I get the db instance without parsing the URL to get the database name from the connection?

like image 674
Joey Yi Zhao Avatar asked Jul 06 '18 03:07

Joey Yi Zhao


1 Answers

In current mongodb driver. The Db class instance has databaseName property. So getting database name that MongoClient was initialized is simply

const db = mongoClient.db();
const dbName = db.databaseName;

Nodejs driver Db documentation

like image 87
Mike Brant Avatar answered Oct 13 '22 00:10

Mike Brant