Nathan H
Nathan H

Reputation: 49371

Database in MongoDB connection string

In the MongoDB Nodejs driver, I see some confusion in what the connection URI can be.

On one hand, in the page describing the URI (https://docs.mongodb.com/manual/reference/connection-string/) it says the the path parameter is the "authentication database".

On the other hand, in many of the official examples (http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#mongoclient-connect) it seems they are using the path parameter as the active database to use (they call db.collection() straight away, without calling .database().

Am I missing something?

Upvotes: 0

Views: 560

Answers (1)

Tunmise Ogunniyi
Tunmise Ogunniyi

Reputation: 2573

TL;DR:
Calling db.collection() immediately after connection only works in versions of the driver less than 3.0.

Details:
Firstly, the official examples you sighted were from MongoDB driver at version 1.4.9, the driver is now at version 3.5.8, I would suggest you check out the latest documentation and examples here.

To clarify the confusion, the database path specified in the connection URI is the authentication database i.e the database used to log in, this is true even for the 1.4.9 version of the driver - reference.

However, the reason for the difference you mentioned, i.e being able to call db.collection() immediately after a connection in some cases is a result of the change in the MongoClient class in version 3 of the driver - reference.

Before version 3, MongoClient.connect would return a DB instance to its call back function and this instance would be referencing the database specified in the path of the connection URI, so you could call db.collection() straight away:

MongoClient.connect("<connection_URI>", function(err, db) {
  // db is a DB instance, so I can access my collections straight away:
   db.collection('sample_collection').find();
});

However, an update was made at version 3 such that, MongoClient.connect now returns a MongoClient instance not a DB instance anymore - reference:

MongoClient.connect("<connection_URI>", function(err, client) {
  // client is a MongoClient instance, you would have to call 
  // the Client.db() method to access your database
  const db = client.db('sample_database');
  // Now you can access your collections
  db.collection('sample_collection').find();
});

Upvotes: 1

Related Questions