How to do double referencing in mongoose schema in Nestjs without forming a circular dependency?

531 views Asked by At

author.module.ts

@Module({
  imports: [
    forwardRef(() => ArticleModule),
    MongooseModule.forFeature([{ name: Author.name, schema: AuthorSchema }]),
  ],
  controllers: [AuthorController],
  providers: [AuthorService, AuthorsRepository, UtilService],
  exports: [AuthorService],
})
export class AuthorModule {}

article.module.ts

  @Module({
  imports: [
   forwardRef(() => AuthorModule),
    CityModule,
    // BookmarkModule,
    MongooseModule.forFeature([{ name: Article.name, schema: ArticleSchema }]),
  ],
  controllers: [ArticleController],
  providers: [ArticleService, ArticlesRepository],
})
export class ArticleModule {}

author.schema.ts (partial file)

@Schema(DefaultSchemaConfig)
export class Author extends BaseSchema {
  @ApiPropertyOptional()
  @IsString()
  @Prop()
  name?: string;

  @ApiPropertyOptional({ type: ArticleRefDto, isArray: true })
  @IsArray()
  @Prop({ type: [{ type: MongooseSchema.Types.ObjectId, ref: 'Article' }] })
  articles?: ArticleRefDto[];
}
export type AuthorDoc = Author & Document;
export const AuthorSchema = SchemaFactory.createForClass(Author);

article.schema.ts

@Schema(DefaultSchemaConfig)
export class Article extends BaseSchema {
  @ApiProperty()
  @IsString()
  @Prop({ required: true })
  title!: string;

  @ApiPropertyOptional({ type: AuthorRefDto })
  @Prop({
    type: MongooseSchema.Types.ObjectId,
    ref: 'Author',
    index: true,
    sparse: true,
  })
  author?: AuthorRefDto;
}

export type ArticleDoc = Article & Document;
export const ArticleSchema = SchemaFactory.createForClass(Article);

I need to reference articledto in author schema and vice versa. But it forms a circular dependency in it and throws the error
class ArticleDto extends article_schema_1.Article { ^

TypeError: Class extends value undefined is not a constructor or null

I tried the forward-Referencing but it doesnt work still shows the same error. I have tried the simple ref method in the schema without forwardref still throws the same error.

I need to do double mapping in both the schemas and tried every possible solution i could find. Let me know if you need more information for the solution

0

There are 0 answers