Multiple MongoDB Connections
To have multiple MongoDB connections one needs to add a connectionName
string to forRoot
and forFeature
.
forRoot
usage
app.module.ts
import { Module } from "@nestjs/common";
import { TypegooseModule } from "@m8a/nestjs-typegoose";
@Module({
imports: [
TypegooseModule.forRoot("mongodb://localhost:27017/otherdb", {
connectionName: "other-mongodb"
}),
CatsModule
]
})
export class ApplicationModule {}
cat.module.ts
@Module({
imports: [TypegooseModule.forFeature([Cat], "other-mongodb")],
controllers: [CatsController],
providers: [CatsService]
})
export class CatsModule {}
Here the CatsService will use the other-mongodb
connection defined in the forRoot
.
forRootAsync
usage
Same cat.module.ts as above for the forFeature
.
cat.module.ts
@Module({
imports: [TypegooseModule.forFeature([Cat], "other-mongodb")],
controllers: [CatsController],
providers: [CatsService]
})
export class CatsModule {}
And for forRootAsync
add connectionName
to the options as well.
@Module({
imports: [
TypegooseModule.forRootAsync({
connectionName: "other-mongodb",
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
uri: configService.getString("MONGODB_URI"),
// ...typegooseOptions (Note: config is spread with the uri)
}),
inject: [ConfigService]
})
]
})
export class CatsModule {}
Added in 11.1.0 - You can now inject a connection into your services.
You can now inject a connection inside of your services, when needed.
import { Injectable } from '@nestjs/common';
import { InjectConnection } from '@m8a/nestjs-typegoose';
import { Connection } from 'mongoose';
@Injectable()
export class CatsService {
constructor(@InjectConnection() private connection: Connection) {}
}