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

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

本文关键字:数据库 驱动程序 mongodb js- node      更新时间:2023-09-26

我对这件事很陌生,只是被困在一个偏僻的地方。我使用本机节点mongodb,并且需要切换到另一个数据库(在对admindb进行身份验证之后(。我在谷歌上搜索到了这个主题,库的创建者建议在散列中为每个数据库保持一个连接。所以我的问题是——我该如何做到这一点?

只需创建不同的数据库连接并将它们存储在一个对象中。

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

这有道理吗?

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