5

I am trying to implement a feature which a user can decide on login to which DB to connect. As it is a web-app, running on a server which all the clients approach, how can I implement this feature without changing every client DB?

At our company we are using mongoose as the MongoDB API. I read all the docs, and didn't notice any functionality for using multiple connections to different DB's on different hosts within the same App at once - without damaging other's client work.

The most valuable thing I have accomplished is to open few connections based on multiple mongoose instances, based on this post: Mongoose and multiple database in single node.js project

I have created few files for example:

var mongoose = require('mongoose');
mongoose.createConnection('mongodb://10.20.100.71:27017/DB_NAME');
module.exports = exports = mongoose;

And then I required them:

let stageAccess = require('./databsesConnections/stageAccess');
let prodAccess = require('./databsesConnections/prodAccess');

I debugged the files and checked the connections are establishing. Further more I checked in the mongoose docs and concluded that I can choose which connection is the default connection, as the docs state: "Mongoose creates a default connection when you call mongoose.connect(). You can access the default connection using mongoose.connection."

So I tried:

mongoose.connection = mongoose.connections[1];

And it works fine.

So the actual question is, what will happen if client 1 approach the app, select to connect dbNum1 and starts to work, then client 2 approach the app and select to connect to dbNum2?

chen20032
  • 115
  • 2
  • 10
  • how about running 2 instances of your application each connected to a different database. then manage clients requests with a load balancer(like HAProxy) by a header which specifies their desirable database. – Mosius Jul 10 '19 at 13:34
  • How would I run multiple instances of my application on the same server? Do you mean something like cluster.fork? And then I should communicate between the clusters? – chen20032 Jul 10 '19 at 13:58
  • Probably the number of users would be equal to the number of mongodb databases. So you can store the name of the database in the users collection. This user collection will be the parent one. So for every app connection you first extract db name from the users collection and then establish then `mongoose.connection`. – Ashh Jul 10 '19 at 16:45
  • @chen20032 you can use some tools like pm2 or start the API on various ports. – Mosius Jul 11 '19 at 08:14
  • 1
    You could use just a single connection and switch database at runtime with [Connection.UseDb method](https://mongoosejs.com/docs/api.html#connection_Connection-useDb). Each `UseDb` returns a new connection object to the specified database so there's no worry about disturbing other active sessions. – Tunmee Sep 16 '20 at 11:54

0 Answers0