Search code examples
mongoosenestjsnestjs-mongoose

NestJs - How to use the same schema & collection for different connections?


I need to establish two different connections to the same mongodb, but with different connection options (poolSize, readPreference, etc.) of course with different connectionName. The MongooseModules are imported in the AppModule

@Module({
  imports: [CustomMongooseDynamicModule, CustomSlavegooseDynamicModule, ...],
  ...
})
export class AppModule {}

Then in some other module I would like to use the same schema/model for each of these connections - note that collection names are the same, connection names are different

@Module({
  imports: [
    MongooseModule.forFeature([{ name: "ABC", schema: AbcSchema }], "main"),
    MongooseModule.forFeature([{ name: "ABC", schema: AbcSchema }], "slave"),
  ],
  controllers: [SomeController],
  providers: [SomeService]
})
export class SomeModule {}

The question is - how can I inject the model into the SomeService for 'main' & 'slave' connection separately?

@InjectModel('ABC') private readonly abcModel: Model<AbcDocument>,
@InjectModel('ABC') private readonly abcSlaveModel: Model<AbcDocument>, ???

Solution

  • You can see the second parameter connectionName if you look at the @InjectModel decorator declaration.

    export declare const InjectModel: (model: string, connectionName?: string | undefined) => (target: object, key: string | symbol, index?: number | undefined) => void;
    

    So you need to pass the connection name as the second parameter.

    @InjectModel('ABC', 'main') private readonly abcModel: Model<AbcDocument>,
    @InjectModel('ABC', 'slave') private readonly abcSlaveModel: Model<AbcDocument>, ???