Using Multiple MongoDB Databases in a Single Server with Node.js and TypeScript

Chukwuemeka Maduekwe
2 min readJul 7, 2023

--

Setting up multiple MongoDB databases in a single Typescript Nodejs Server somes with a lot of advantages, ranging from:

  1. Data segregation
  2. Scalability and performance
  3. Security and access control
  4. Data isolation
  5. Third-party integration
  6. Testing and development
  7. Future-proofing and modularity

NB: Here’s a link to the repo where I’m actively using multiple databases in production (SoccerMASS) just in case you need a reference to learn from.

In this app what I did was to create a separate database for Accounts (profile creation, signin signup, etc.), Manager (club, player, manager data in SoccerMASS game — Soccer Manager) Console (App logs, contact messages, advertisment, error logs, etc. ) and ApiHub (Data for all public endpoints).

In this application we used mongoose, but just in case you need to use MongoDB methods directly, that would also work.

We create our schema using mongoose like in most app, the code is self explanatory, but just to higlight a few stuff. ProfileSchema describes the structure of our data in Profile collection, while all methods in profile schema statics can be called directly from using the profile model. The pre method attached to ProfileSchema intercepts all records and can manipulate them before they are saved to the database. Finally we export our model for use in our app. The code above can be found on github here just in case its updated in the future.

You can find more Schemas and Models in the models folder inside the src file

This code actually creates a connection event for our databases, and can also be used to log data here. Inside the snippet above we connect to our different databases and export them for use in our app. The code can be found here.

More content at PlainEnglish.io.

Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.

--

--

No responses yet