Connecting Multiple Databases to NestJS Application
Nest JS is a popular Node framework used to develop API’s. It has all the advanced in-built modules for Security (Authentication, Authorization, Encryption), Queues, Caching, etc..
In common, applications connect to a single database, but it isn’t a limitation. At times, we might need to connect a second or a third database depending on the requirement. One such good example is given in the below architecture
In the above example, our Nest App connect to 2 Databases, i.e User Database for validating user credentials and fetching their roles and profile, Records Database to fetch the actual application data. This architecture is very common while working with Micro Services
Before we go deep, let’s also discuss on ORM (Object Relational Mapping), Most of us have worked with ORM which is a programming technique that facilitates interaction with databases through an object-oriented approach, abstracting the complexities of SQL queries and relational database management
In our example, we are going to connect our Nest App using TypeORM(Very Popular ORM with JS) to the first DB, the code is as below, and later we will continue with the approach which allows us to connect our App to a second Database.
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
const envData = process.env;
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mssql',
host: envData.db_host,
port: envData.db_port,
username: envData.db_username,
password: envData.db_password,
database: envData.db_name,
// Other ORM Configuration
})
// Other Modules,
],
controllers: [
// Controllers
],
})
export class AppModule {}
In the code above, we can observe that TypeORM gives inbuilt methods to add DB configuration, It’s always better to get these configuration variables from environment files, and even better to get them from Secret Managers/ Vaults like AWS Secret Manager, HashiCorp Vault etc..
To learn more on “Managing Secrets with HashiCorp Vault & Nest Application” . Click here
TypeORM has to be imported as a dependency at our parent module, this is where we can also start making configurations to connect to a secondary database. Please find the below snippet
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
const envData = process.env;
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mssql',
host: envData.db_host,
port: envData.db_port,
username: envData.db_username,
password: envData.db_password,
database: envData.db_name,
}),
TypeOrmModule.forRoot({ // This is our Second DB Config
name: "secondDB", // Unique name
type: 'mariadb',
host: envData.db_host2,
port: envData.db_port2,
username: envData.db_username2,
password: envData.db_password2,
database: envData.db_name2,
}),
// Other Modules
],
controllers: [
// Controllers
],
})
export class AppModule {}
In the above example, in order to connect to a secondary database, we need to add a new variable called “name” which will help us to differentiate both connections. TypeORM not only to connects with similar databases, but it even allows us to connect multiple datasources like mysql, mariadb, mssql, mongodb, postgres etc..
Now let’s see how to use this while working with Child Modules
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
@Module({
imports: [
TypeOrmModule.forFeature([
// Entities (Primary DB)
]),
TypeOrmModule.forFeature([
// Entities (Second DB)
], "secondDB"),
],
controllers: [
// Controllers
],
providers: [
// Providers
],
})
export class ChildModule {}
Let’s see how to use this while working with Providers
constructor(
@InjectRepository(TrnProcessRecord, "secondDB")
private trnProcessRecordRepository: Repository<TrnProcessRecord>,
@InjectRepository(BrnRecord)
private brnProcessRecordRepository: Repository<BrnRecord>
) { }
Note: To connect to the first DB, we don’t need to specify any “name” as that would be the default connection if not particularly specified
It’s good to restart your application and now you should be able to work with multiple Databases 😇
👏 If you enjoyed reading this blog post, don’t forget to give it a round of applause! Your support means a lot to us. Also consider following for more insightful content