Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript MongoDB/Express-通过connect()连接后如何切换数据库_Javascript_Mongodb_Express - Fatal编程技术网

Javascript MongoDB/Express-通过connect()连接后如何切换数据库

Javascript MongoDB/Express-通过connect()连接后如何切换数据库,javascript,mongodb,express,Javascript,Mongodb,Express,我正在使用express连接到我的mongoDB: mongodb.MongoClient.connect(mongourl, function(err, database) { // How would one switch to another database here? }); 我必须首先连接到管理数据库。在协议建立之后,我想切换数据库 虽然我已经翻遍了官方文件,但还是找不到适合我需要的东西 我知道MongoClient::open()方法,但我想继续使用connect

我正在使用express连接到我的mongoDB:

mongodb.MongoClient.connect(mongourl, function(err, database) {

      // How would one switch to another database here?

});
我必须首先连接到管理数据库。在协议建立之后,我想切换数据库

虽然我已经翻遍了官方文件,但还是找不到适合我需要的东西

我知道
MongoClient::open()
方法,但我想继续使用
connect()


非常感谢您的帮助。

您只需再次调用
MongoClient.connect
,因为每个数据库都有一个连接。这意味着您不能更改现有连接的数据库。您必须再次连接:

mongodb.MongoClient.connect(mongourl, function(err, database) {
    mongodb.MongoClient.connect(mongourl_to_other_database, function(err, database2) {
        // use database or database2
    });
});

您可以切换到另一个数据库,如下所示:

mongodb.MongoClient.connect(mongourl, function(err, database) {
  // switch to another database
  database = database.db(DATABASE_NAME);
  ...
});
()

编辑:澄清一下:这还允许您通过同一连接打开多个数据库:

mongodb.MongoClient.connect(mongourl, function(err, database) {
  // open another database over the same connection
  var database2 = database.db(DATABASE_NAME);

  // now you can use both `database` and `database2`
  ...
});

所以我这里有两个观点,哪一个是正确的选择?这取决于你是否想并行使用这两个(或更多)数据库。如果你只切换一次,你可以采用罗伯特克莱普的解决方案。如果您一直在siwtching,那么保持多个数据库连接处于打开状态(我的解决方案)可能是一个更好的主意clarification@heinob您可以使用我的答案中的方法在同一连接上打开多个数据库。我编辑了我的答案以澄清这一点。我还想知道如何能够从不同的函数中更改数据库和集合-您可以只创建一个全局实例并“更新它”,还是每次调用函数时都运行
mongodb.MongoClient.connect…
(这可能是通过单击事件从数据库获取文档等)?我拒绝执行后一种操作,因为这似乎需要进行大量连接!请注意,这将“创建一个共享当前套接字连接的新Db实例”,并且“新的db实例与原始实例以父子关系相关联,以便在子db实例上正确发出事件”。此外,“缓存子db实例,以便执行两次db('db1')将返回同一实例。”。因此,在生产中使用此方法之前,请仔细阅读文档,因为关闭一个“子”db上的连接可能会一次“关闭”多个db。您可以在源代码中找到有关分层
close
方法的实现详细信息。