Multiple MongoDB database Connections in NodeJS

Hello, I have always created a single connection with one connection string. My question is, how to create multiple connections(MongoDB instances) if an array of connection strings are given in NodeJs get API?

Let’s say multiple connection strings will have the same type of database. e.g., my database name is “University” and this database is available in all different locations. And I wanted to write one common API which will provide me with an array of universities from different connections, how to do it?

Example connectionString1 = mongodb://localhost:27017
connectionString2 = mongodb://localhost:27018
connectionString3 = mongodb://localhost:27019

Now I wanted to connect with all three connection strings and fetch all records from it and send it
in a response to one common API, how can I do it in an efficient manner?

Your input will help me to understand this structure in better way

1 Like

This line is the heart of the connection:
const client = new MongoClient(uri);

new operator will give you a new object each time so you would need:

const client1 = new MongoClient(uri1);
const client2 = new MongoClient(uri2);
const client3 = new MongoClient(uri3);

unfortunately, the rest is not this easy. for each function in CRUD, you have to implement your own logic to integrate them.

  • Write to all at once, becomes replicas, but hard to maintain.
    • Write to a random one. would also be easier to merge
  • Read from all and combine. sounds easy. simple object merge. but careful not to insert a document into two and later update just one.
  • Update is the same as write but not random. tell them all to update a match at once. or find exactly which server has that data first.
  • Delete should be easy but be cautious with your query as usual. ask all connections if they have that match and delete them.