0

I have created a new NestJS v9 project, reusing a WORKING module from my previous NestJS v8.2.4 (as part of my research on upgrading to NestJS v9 eventually) but it doesn't compile, claiming it can't find my imported Mongoose model (happens with any module that has a model):

Nest can't resolve dependencies of the SystemService (?). Please make sure that the argument SystemConfigModel at index [0] is available in the SystemModule context.

I've created a sample based on the nestjs tutorial (using cats module instead of my system module) in code sandbox where the error is reproduced

app module:

@Module({
  imports: [
    SystemModule,
    MongooseModule.forRoot(`mongodb://localhost/db1`, {
      connectionName: 'mydb',
    }),

  ],
  controllers: [AppController],
  providers: [AppService, AppResolver],
})
export class AppModule {}

system module (listing all classes together):

export type SystemConfigDocument = mongoose.HydratedDocument<SystemConfig>;

@Schema()
export class SystemConfig {
    @Prop()
    key: string;

    @Prop()
    value: string;
}

export const SystemConfigSchema = SchemaFactory.createForClass(SystemConfig);


@Module({
    imports: [
        MongooseModule.forFeature(
            [
                {
                    name: SystemConfig.name,
                    schema: SystemConfigSchema,
                    collection: 'systemConfig',
                },
            ],
            'mydb',
        ),
    ],
    providers: [SystemService],
    exports: [SystemService],
})
export class SystemModule {}


@Injectable()
export class SystemService {
    constructor(
        @InjectModel(SystemConfig.name) private systemConfigModel: Model<SystemConfig>,
    ) {}
}
Sagi Mann
  • 2,967
  • 6
  • 39
  • 72

2 Answers2

0

When using a named database, just like you pass the database name to the forFeature() method, you haveto pass it as a second parameter to the @InjectModel() decorator. e.g. @InjectModel(SystemConfig.name, 'mydb')

Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147
0

Got a reply from NestJS team about it: connectionName is the problem. Basically, since I'm using a custom connection name mydb in the app module, InjectModel needs to explicitly specify the connection name as well. My project DOES have multiple connections, so what I can do, is use the most common connection as the default one and therefore, in most cases, InjectModel will not need to specific an explicit connection:

app module:

  imports: [
    SystemModule,
    MongooseModule.forRoot(`mongodb://localhost/db1`),
  ],
Sagi Mann
  • 2,967
  • 6
  • 39
  • 72