Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS - Use multiple MongoDB connections per module

Is there a way to connect multiple MongoDB connections per module?

app.module.ts

@Module({
  imports: [
    MongooseModule.forRoot('mongodb://localhost/masterDB'),
    UserModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule { }

Similarly, can we define another connection in another module which is a child of app.module?

child.module.ts

@Module({
  imports: [
    MongooseModule.forRoot('mongodb://localhost/childDB'),
    MongooseModule.forFeature([{ name: 'child', schema: ChildSchema }]),
  ],
  controllers: [ChildController],
  providers: [ChildService],
})
export class ChildModule { }

Or any other way to access different databases at once.

Thanks in advance!

like image 994
Ank Avatar asked Oct 18 '25 17:10

Ank


1 Answers

[SOLVED March 2021]

Here you'll find the solution:

https://www.learmoreseekmore.com/2020/04/nestjs-multiple-mongodb-databases.html

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { studentSchema } from './schemas/myworld/student.schema';
import { animalSchema } from './schemas/wildlife/animal.schema';

@Module({
  imports: [
    MongooseModule.forFeature([
      {
        name: 'Student',
        schema: studentSchema,
        collection: 'Student',
        
      },
    ],'myWorldDb'),
    MongooseModule.forFeature([
      {
        name: 'Animals',
        schema: animalSchema,
        collection: 'Animals'
      }
    ],'wildLifeDb'),
    MongooseModule.forRoot(
      'mongodb+srv://<userName>:<password>@cluster0-igk.mongodb.net/MyWorld?retryWrites=true&w=majority',
      {
        connectionName: 'myWorldDb'
      }
    ),
    MongooseModule.forRoot(
      'mongodb+srv://<username>:<password>@cluster0-igk.mongodb.net/WildLife?retryWrites=true&w=majority',
      {
        connectionName: 'wildLifeDb'
      }
    )

  ],
  controllers: [],
  providers: [],
})
export class AppModule {}
like image 160
Despertaweb Avatar answered Oct 20 '25 07:10

Despertaweb