简体   繁体   English

node.js - 如何在 mongodb 驱动程序中切换数据库?

[英]node.js - how to switch a database in mongodb driver?

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).我正在使用node-mongodb-native并且需要切换到另一个数据库(在对 admin db 进行身份验证之后)。 I googled and found this topic where the creator of library recommends to keep a connection for each db in a hash.我用谷歌搜索并找到了这个主题,图书馆的创建者建议在 hash 中为每个数据库保持连接。 So my question is - how do I accomplish it?所以我的问题是 - 我该如何完成它?

Just create different database connections and store them in an object.只需创建不同的数据库连接并将它们存储在 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 :Db下的 MongoDB 驱动程序文档中隐藏了一个示例:

[...]
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");

  [...]
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM