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?
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
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