5

I'm new to this stuff and just stuck in the middle of nowhere. Am using node-mongodb-native and am in need to switch to another database (after authentication against admin db). I googled and found this topic where the creator of library recommends to keep a connection for each db in a hash. So my question is - how do I accomplish it?

rim84
  • 51
  • 1
  • 2

2 Answers2

3

Just create different database connections and store them in an object.

var dbConnections = {};

var dbConnections.authDb = new Db('adminDb', server, {});
dbConnections.authDb.authenticate(username, password);

var dbConnections.otherDb = new Db('otherDb', server, {});

Does that make sense?

Clint
  • 2,871
  • 2
  • 25
  • 28
1

There's an example hidden in the MongoDB driver docs under Db:

[...]
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  [...]

  // Reference a different database sharing the same connections
  // for the data transfer
  var secondDb = db.db("integration_tests_2");

  // Fetch the collections
  var multipleColl1 = db.collection("multiple_db_instances");
  var multipleColl2 = secondDb.collection("multiple_db_instances");

  [...]
});
Morten Siebuhr
  • 6,068
  • 4
  • 31
  • 43