MongoClient.connect in 3.0: how to continue to use the database name in the connection string like in 2.x?

38 views
Skip to first unread message

mar...@gmail.com

unread,
Jan 15, 2018, 5:38:57 PM1/15/18
to node-mongodb-native
In 2.x we're used to connecting to a connection string which specifies the database name:

MongoClient.connect('mongodb://localhost:27017/myDatabase', (err, db) => {
 
// Database returned (it's "myDatabase" as specified in the connection string)
});

In 3.0 there is now an extra step: calling client.db() with the database name, explicitly.

MongoClient.connect('mongodb://localhost:27017/myDatabase', (err, client) => {
 
// Client returned
  var db = client.db('myDatabase'); // We have to repeat the database name here
});

How can we continue to use the database name that's already in the connection string?  It's useful to keep the connection configuration to just 1 string, and not having to parse it out manually.

Right now I imagine a solution where I parse the database name out of the connection string which I pass to connect(), and then pass that to client.db(). But if MongoClient is already parsing the connection string internally, this seems like redundant work. Is there a simpler way?

pirxpilot

unread,
Jan 16, 2018, 9:51:52 AM1/16/18
to node-mongodb-native
Came here to look for this :-)
Perhaps `client.db()` could connect to the database specified in the connection URL? I'll gladly send a patch to that effect if that does not break something I don't see.

In the meantime - just looking at the code - you can get to the parsed `dbName` from the client instance.

MongoClient.connect('mongodb://localhost:27017/myDatabase', (err, client) => {
  var dbName = client.s.options.dbName; // ugly HACK here
  var db = client.db(dbName);
});

But that of course will stop working when MongoClient code changes.
D.
Reply all
Reply to author
Forward
0 new messages