When I initiate my Express app, I define all required parameters in Environmental Variables.
According to code here:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
To get a database object I need:
- To pass database name when I initialize my application. One more
environment variable, don't like it. - To parse
URIobject like this:mongodb://localhost:27017/myprojectto extract database name. One more line of code, don't like it either.
Is there another 3rd solution? When I tried to debug client object which returned if connection was successful I've seen that it already contains name of the database connected to see screenshot below, but I haven't found any official API how to use it. Use a "hacky" way I don't like too.

I don't like itis a valid objection. Either way, the API needs a database name, it's just how it works. FWIW, it's more common in practice to provide it as part of the URI in the environment variables and parse it from there than it is to provide it separately.dbNamefrom that URI will ever change.