Multiple MongoDB database Connections in NodeJS

Abhishek Singh
2 min readJul 22, 2019

--

MongoDB allows configuring a secondary replica node to be hidden. It means that the secondary replica node will not be elected as Primary in case of primary node failure. Wait… But why we need such a replica node? The answer is that the application can transfer its analytics(read heavy) queries to this node so the primary node will not suffer any hiccup because of heavy read analytics queries.

Here We will be looking into how to connect to this node in NodeJs for read-heavy queries.

Read more about it on below links.

Configure Multiple connections:

let's start. Create these files inside the DB folder.

1: Create db.primary.js file. This is the default Connection.

2: Create db.secondary.js file. The connection you are plugging into an application.

3: Create index.js file. This file will export all database connections.

This will create a Read connection(secondary) and Primary connection. As it is a read-only connection so you need only collection names in a model, not actual Schema.

4: Your folder structure should look like this.

5: Initialize Database connection in server.js file as You would do with default connection. Make sure to comment out old database import.

Now your database connections are done.

Start using it by calling getModels method by importing wherever needed.

--

--