mongoose - Lazy loaded module and Service InjectModel - Stack Overflow

admin2025-04-17  2

I have a lazy loaded module in App module:

@Module({
  imports: [
    ThrottlerModule.forRoot([
      {
        ttl: 60,
        limit: 5,
      },
    ]),
    ConfigModule.forRoot({
      isGlobal: true,
      load: [databaseConfig],
    }),
    MongooseModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        uri: configService.get<string>(CONFIGS.DATABASE_URI),
      }),
    }),
    forwardRef(() => import("./auth/auth.module").then((m) => m.AuthModule)),
    forwardRef(() => import("./admin/admin.module").then((m) => m.AdminModule)),
    forwardRef(() =>
      import("./accounts/accounts.module").then((m) => m.AccountsModule),
    ),
  ],
  controllers: [AppController],
  providers: [
    AppService,
    {
      provide: APP_GUARD,
      useClass: ThrottlerGuard, // Applying global throttle guard
    },
  ],
})
export class AppModule {}

Now in Accounts Module I have

@Module({
  imports: [
    MongooseModule.forFeature([{ name: Account.name, schema: AccountSchema }]),
  ],
  providers: [AccountsService],
  controllers: [AccountsController],
  exports: [AccountsService],
})
export class AccountsModule {}

The issue is in the service when I inject model:

@Injectable()
export class AccountsService {
  constructor(
    @InjectModel("Account") private readonly accountModel: Model<Account>,
  ) {}
}

I get this error:

[Nest] 39564 - 01/31/2025, 8:37:04 AM ERROR [ExceptionHandler] UnknownDependenciesException [Error]: Nest can't resolve dependencies of the AccountsService (?). Please make sure that the argument "AccountModel" at index [0] is available in the AccountsModule context.

Potential solutions:

  • Is AccountsModule a valid NestJS module?
  • If "AccountModel" is a provider, is it part of the current AccountsModule?
  • If "AccountModel" is exported from a separate @Module, is that module imported within AccountsModule? @Module({ imports: [ /* the Module containing "AccountModel" */ ] })

Account schema is below for reference:

@Schema()
export class Account extends Document {
  @Prop({ required: true })
  name: string;

  @Prop({ required: true })
  type: string;

  @Prop({ required: true })
  ownerId: string; // Cognito User ID

  @Prop({ default: Date.now })
  createdAt: Date;
}

export const AccountSchema = SchemaFactory.createForClass(Account);
转载请注明原文地址:http://anycun.com/QandA/1744880713a88936.html