MongoDB / Express - 通过connect()连接后如何切换数据库 [英] MongoDB / Express - How to switch database after connecting via connect()

查看:56
本文介绍了MongoDB / Express - 通过connect()连接后如何切换数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用express连接到我的mongoDB:

I am using express to connect to my mongoDB:

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

      // How would one switch to another database here?

});

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

I have to connect to the admin database in the first place. After the conenction has been established, i would like to switch the database.

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

Although i have searched through the official documentation, i was unable to find something that fits my needs.

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

I am aware of the MongoClient::open() method, but i would like to stick to connect().

感谢任何帮助。

推荐答案

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

You can switch to another database like so:

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

docs

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

EDIT: for clarification: this also allows you to open multiple databases over the same connection:

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

这篇关于MongoDB / Express - 通过connect()连接后如何切换数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆