MongoDB / Express - How to switch database after connecting via connect()
express, javascript, mongodb
Solution
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`
...
});
Problem
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.