'Nest JS Circular Dependency Issue - Mongoose Module

I am trying to inject dependencies in mongoose module for root async. I want to kind of simulate a cascade delete using mongoose hooks.

I have this module, which imports mongoose module, and it imports other modules.

@Module({
  imports: [
    MongooseModule.forFeatureAsync([
      {
        imports: [NotificationModule, UserModule, MuseumModule, ImageModule, CommentModule],
        name: Shirt.name,
        useFactory: (
          NotificationService: NotificationService,
          UserService: UserService,
          MuseumService: MuseumService,
          ImageService: ImageService,
          ConfigService: ConfigService,
          CommentService: CommentService,
        ) => {
          const schema = ShirtSchema;
          schema.post('findOneAndDelete', async function (document: ShirtDocument) {
            /* Delete notifications */
            if (document) {
              await NotificationService.deleteManyFromArray(document._id);

              /* Remove shirt from museum */
              const shirtUser = await UserService.getById(document.shirtUser.userId);
              await MuseumService.removeShirtByMuseumId(shirtUser.museums[0], document._id);

              /* Delete images from bucket */
              if (document.images && document.images.length > 0) {
                document.images.forEach(async (image) => {
                  if (image.thumbnail) {
                    await ImageService.deleteImageFromBucketS3({
                      bucket: ConfigService.get('AWS_THUMBNAIL_BUCKET'),
                      key: getImageUUID(image.thumbnail),
                    });
                  }
                  await ImageService.deleteImageFromBucketS3({
                    bucket: ConfigService.get('AWS_BUCKET'),
                    key: getImageUUID(image.cloudImage),
                  });
                });
              }

              /* Remove shirt comments */
              if (document.comments && document.comments.length > 0) {
                await CommentService.deleteManyComments(document.comments.map((c) => c._id));
              }
            }
          });
          return schema;
        },
        inject: [NotificationService, UserService, MuseumService, ImageService, ConfigService, CommentService],
      },
    ]),
    UserModule,
    TeamModule,
    BrandModule,
    CountryModule,
    MuseumModule,
    ImageModule,
  ],
  controllers: [ShirtController],
  providers: [ShirtService, ShirtRepository],
  exports: [ShirtService],
})
export class ShirtModule {}

I also need to do the same in another module, but when I import the

ShirtModule

the compilation fails with the following error:

Error: Nest cannot create the module instance. Often, this is because of a circular dependency between modules. Use forwardRef() to avoid it. Scope [AppModule -> UserModule -> MongooseModule -> MuseumModule -> MongooseModule -> ShirtModule -> MongooseModule]

@Module({
  imports: [
    MongooseModule.forFeatureAsync([
      {
        name: 'Museum',
        imports: [ShirtModule],
        useFactory: () => {
          const schema = MuseumSchema;
          schema.post('findOneAndDelete', async function (document: MuseumDocument) {});
          return schema;
        },
      },
    ]),
  ],
  controllers: [MuseumController],
  providers: [MuseumService, MuseumRepository],
  exports: [MuseumService],
})
export class MuseumModule {}

I tried using

forwardRef(() => )

In both modules, but still the same. I can not understand where is the circular dependency and how to solve it. Please could you help me?. Also, is this is a good approach to use mongoose hooks using nest? Thanks



Solution 1:[1]

Try to use forwardRef(() => MongooseModule.forFeatureAsync(xxxx)). This is work in my case.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pppppu