0

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:

  1. To pass database name when I initialize my application. One more environment variable, don't like it.
  2. To parse URI object like this: mongodb://localhost:27017/myproject to 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.

enter image description here

3
  • 1
    I fail to see why I don't like it is 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. Commented Feb 6, 2018 at 17:21
  • The more effort you make to cause something to work (more code, more variables) it's more error-prone, see this youtube.com/watch?v=oHcToNCn4K8 Commented Feb 6, 2018 at 19:07
  • This is a trivial complication. It's something you need to write once and never have to touch again. It's not like parsing a dbName from that URI will ever change. Commented Feb 6, 2018 at 21:22

1 Answer 1

1

This is now simply done by simply not passing any variable to client.db().

As documentation states out:

The name of the database we want to use. If not provided, use database name from connection string.

http://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html#db

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.