MongoDB / Express - How to switch database after connecting via connect()

前端 未结 2 931
时光说笑
时光说笑 2021-01-03 06:26

I am using express to connect to my mongoDB:

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

      // How would one switch to another databa         


        
2条回答
  •  心在旅途
    2021-01-03 07:14

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

提交回复
热议问题