NodeJS

How to connect multiple database in NodeJS


Why do we use multiple databases ?

- multiple databases are useful in various situation

1) Microservice architecture: when each service has its own database.

2) Data segregation: You may need separate databases for different modules (e.g., userProducts, users).

3) Different Database Types: Connecting to both SQL and NoSQL databases in the same project.

 

Prerequisites

 

  • Node.js installed.
  • TypeORM and the required database drivers installed.
  • Basic knowledge of Node.js and TypeORM.
  •  

connect multiple database in node with typeORM

Follow This Steps:

1) Step 1: Install Required Dependencies.

      Note: Ensure you have TypeORM and the necessary database drivers for the databases    you’re connecting. Example, PostgreSQL and MySQL.     npm install typeorm @nestjs/typeorm pg mysql2  

2) Step 2: Create the Project

       /src                 /entities                    userCart.ts                    userProducts.ts                /modules                    userCart.module.ts                     product.module.ts               app.module.ts                main.ts              /ormconfig                ormconfig.userCart.ts                 ormconfig.product.ts                Package.json

3) Step 3: Create ORM Configuration Files

   -  ormconfig.userCart.ts for userCart database         import { DataSource } from 'typeorm';

         import { userCarts } from '../oc/src/shared/entity/userCarts';          export const userCartDataSource = new DataSource({               type: 'postgres',  // database you want to use       host: 'localhost',         port: 5432,                           username: 'userCart_db_user',                          password: 'userCart_db_password',                         database: 'userCart_db',                          entities: [userCarts],                        synchronize: true,                });   - ormconfig.product.ts for product database           import { DataSource } from 'typeorm';import { userProducts } from '/oc/src/shared/entity/userProducts';export const ProductDataSource = new DataSource({  type: 'mysql', // database you want to use  host: 'localhost',  port: 3306,  username: 'userProducts_db_user',  password: 'userProducts_db_password',  database: 'userProducts_db',  entities: [userProducts],  synchronize: true,});

 

  

Step 4: Create Entities for Each Database

 -  userCart.ts Entity for the userCart Database

        import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

                  @Entity()         export class userCart {  @PrimaryGeneratedColumn()  id: number;  @Column(type: 'decimal',{ precision: 7, scale: 3, nullable: true})  totalItem: number;}
  • Product.ts Entity for the Product Database       import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

  @Entity()

export class userProducts {

  @PrimaryGeneratedColumn()

  id: number;

  @Column()

   name: string; }

Step 5: Initialize Data Sources in Your Application

-  made configuration in your app.module.ts     import { Module } from '@nestjs/common';

import { TypeOrmModule } from '@nestjs/typeorm';import { userCartModule } from 'oc/module/userCart.module';import { ProductModule } from 'oc/module/userProducts.module';import { UserDataSource } from 'oc/ormconfig/ormconfig.userCart';import { ProductDataSource } from 'oc/ormconfig/ormconfig.userProducts';@Module({   imports: [     // Import the userCart database connection     TypeOrmModule.forRootAsync({      useFactory: () => userCartDataSource.options,     }),     // Import the product database connection     TypeOrmModule.forRootAsync({       useFactory: () => ProductDataSource.options,     }),     userCartModule,     ProductModule,   ],}) export class AppModule {} 

Step 6: Implement Modules for userCart and Product

 - user.module.ts     import { Module } from '@nestjs/common';

import { TypeOrmModule } from '@nestjs/typeorm';import { userCart } from '../oc/src/shared/entity/userCarts';import { userCartService } from 'oc/user.service';@Module({   imports: [TypeOrmModule.forFeature([userCart])],  providers: [userCartService],})

export class userCartModule {}

  •  product.module.ts

                   import { Module } from '@nestjs/common';

       import { TypeOrmModule } from '@nestjs/typeorm';import { userProducts } from '../oc/src/shared/entity/userProducts';import { userProductservice } from 'oc/product.service';@Module({  imports: [TypeOrmModule.forFeature([userProducts])],  providers: [userProductservice],})export class ProductModule {}

 

Step 7: Implement Services for Handling CRUD Operations

user.service.ts

import { Injectable } from '@nestjs/common';import { InjectRepository } from '@nestjs/typeorm';import { Repository } from 'typeorm';import { userCart } from '../oc/src/shared/entity/userCarts';@Injectable()export class userCartService {  constructor(    @InjectRepository(userCart)    private userCartRepository: Repository<userCart>,  ) {}  finduserCartDetails(): Promise<userCart[]> {    return this.userCartRepository.find();  }}product.service.ts import { Injectable } from '@nestjs/common';import { InjectRepository } from '@nestjs/typeorm';import { Repository } from 'typeorm';import { userProducts } from '../oc/src/shared/entity/userProducts';@Injectable()export class userProductsService {  constructor(    @InjectRepository(userProducts)    private userProductsRepository: Repository<userProducts>,  ) {}  findAll(): Promise<userProducts:[]> {    return this.productRepository.find();  }  create(product: userProducts): Promise<userProducts> {    return this.productRepository.save(product);  }}

Step 8: Run Your Application

npm run start

Ready to transform your business with our technology solutions? Contact us today to Leverage Our NodeJS Expertise.

0

NodeJS

Related Center of Excellence