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

 是个success 发布于 2023-01-30 11:09

我使用express连接到我的mongoDB:

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

      // How would one switch to another database here?

});

我必须首先连接到管理数据库.建立连接后,我想切换数据库.

虽然我搜索了官方文档,但我无法找到符合我需求的东西.

我知道这个MongoClient::open()方法,但我想坚持connect().

任何帮助表示赞赏.

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

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

    (docs)

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

    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`
      ...
    });
    

    2023-01-30 11:11 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有