Creating Dynamic MongoDB Connections in Node.js and Mongoose

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?

For now I have a connection like that:

    // config variables
    const PORT: string = config.get('PORT');
    const MODE: string = config.get('MODE');
    const SESSION_SECRET: string = config.get('SESSION_SECRET');
    const CLIENT_DOMAIN: string = config.get('CLIENT_DOMAIN');
    const ORDER_CLIENT_DOMAIN: string = config.get('ORDER_CLIENT_DOMAIN');
    const AUTH_COOKIE_MAX_AGE: number = config.get('AUTH_COOKIE_MAX_AGE');
    const mongoUrl: string = config.get('mongoURI');
    
    const app = express();
    const server = createServer(app);
    const io = initializeSocketServer(server, {
    	cors: {
    		origin: [CLIENT_DOMAIN, ORDER_CLIENT_DOMAIN],
    	},
    });
    
    //-----------------------------Middleware Start------------------//
    connectDB();

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.

In general, I already implemented it and it is not just a change in the name of the connection.

So the basics of multi-tenant here: Multitenant Node.js Application with mongoose (MongoDB) | by Prakhar Jain | Connected Lab TechBlog | Medium.

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.