0

My NodeJS application has form with text input field (for search) and a dropdown mongo for DEV, UAT and Production database options.

Based on the user selection respective database has to be accessed.

I want to know how to dynamically handle /change different database endpoint or change node env in run-time ?

Selvam Raju
  • 196
  • 4
  • 14

1 Answers1

1

One way that comes to my mind is to disconnect and connect again. If you are using mongoose, do something like:

   var mongoose = require('mongoose')
   ...
   try {
   mongoose.disconnect();
   mongoose.connect(mongoURL);
   catch (e) {
   console.log(e);
   }

every time and take the mongoURL from the user input.

Another way is to use multiple connections:

var mongoose = require('mongoose')
var conn = mongoose.createConnection('mongodb://localhost/db1');
var conn2 = mongoose.createConnection('mongodb://localhost/db2');

and then choose the connection that you want to use depending on the user choice. I prefer this last one.

Take a look at this answer for more info:

https://stackoverflow.com/a/32909008/7041393

hjbello
  • 643
  • 4
  • 18