最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - node.js - how to switch a database in mongodb driver? - Stack Overflow

programmeradmin2浏览0评论

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 remends to keep a connection for each db in a hash. So my question is - how do I acplish it?

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 remends to keep a connection for each db in a hash. So my question is - how do I acplish it?

Share Improve this question asked Jul 6, 2011 at 13:43 rim84rim84 511 silver badge2 bronze badges 1
  • See also stackoverflow./questions/30121148/changing-mongo-database for an alternative solution – Morten Siebuhr Commented Aug 16, 2017 at 11:29
Add a ment  | 

2 Answers 2

Reset to default 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?

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");

  [...]
});
发布评论

评论列表(0)

  1. 暂无评论