Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

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

Any help is appreciated.

like image 814
user2422960 Avatar asked Jan 31 '14 09:01

user2422960


People also ask

How do I connect to a specific database in MongoDB?

Connect to a Single MongoDB Instance const MongoClient = require('mongodb'). MongoClient; const assert = require('assert'); // Connection URL const url = 'mongodb://localhost:27017'; // Database Name const dbName = 'myproject'; // Use connect method to connect to the server MongoClient.

Do I need to close MongoDB connection?

There is no need for closing the connection explicitly. This way the application avoids creating and closing connections (which is an expensive operation).

How does node Express Connect to MongoDB?

To connect a Node. js application to MongoDB, we have to use a library called Mongoose. mongoose. connect("mongodb://localhost:27017/collectionName", { useNewUrlParser: true, useUnifiedTopology: true });


2 Answers

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`
  ...
});
like image 181
robertklep Avatar answered Oct 03 '22 16:10

robertklep


You just have to call MongoClient.connect once again, because there is one connection per database. That means, you cannot change the database of an existing connection. You have to connect a second time:

mongodb.MongoClient.connect(mongourl, function(err, database) {
    mongodb.MongoClient.connect(mongourl_to_other_database, function(err, database2) {
        // use database or database2
    });
});
like image 21
heinob Avatar answered Oct 03 '22 15:10

heinob