I’m working on a Node.js project using Mongoose and MongoDB, and I have a specific use case where I need to create dynamic database connections for different branches. Here’s what I’m trying to achieve:
I have a main database called adminBranches, which stores information
about all the available branches.
When a user logs in, I want to fetch the list of branches available
to that user.
The user should then be able to select a branch to work with, and the
application should establish a connection to the corresponding
branch-specific database.
The selected database connection should be stored in the user’s
session for the duration of their session.
I’ve attempted to set up a global connection, but I’m now looking for guidance on how to create these dynamic connections for each user and branch. Can anyone provide insights or code examples on how to achieve this in Node.js and Mongoose?
Do you mean to different servers/clusters or simply different database/collection name space?
Different database/collection is really just a name and this should be easily part of the session data.
Different servers/clusters (cluster to make the rest of text lighter) is a different ball game. Switching to different database/collection within the same cluster is trivial; database and collection names can easily be part of the session data since it is only a identifier. Switching to a different cluster connection is more involve because there are internal structures (like send/receive buffers/credentials) associated with each connections. Some design patterns like momoization could help achieving this. In the literature, it is mostly use to cache the evaluation of a complex function but I consider establishing a connection a complex function. Is it like a pool of connection pool where each name is associated to a different pool.
But your sample seems to imply a single URI so your case is the trivial one where use a map to map (I do not know how to express that in any other way) a branch name into a list of database/collection names.
So, the most of painful for me here was accepting what for each database we should have connections with ALL models for each but in cache. Provided solution is not working for population, because when it do population we should set that model to use (that tenant).
so in code unfortunately we have to register ALL model in first request for that tenant.