How to do recursion on typeorm relations

Viewed 2459

category.ts

@Entity('categoryenter code here')
export class Category{
  @PrimaryGeneratedColumn({ type: 'int' })
  id: Category;

  @OneToMany(() => Category, category => category.category,{eager:true})
  categoryList: Category[];

  @ManyToOne(() => Category, (category) => category.categoryList)
  category: Category;
}

The Category entity is above(mysql). I want to find a category with all it's children like this

await categoryRepo.findOne({
  where:{ id: 1 },
  relations:['categoryList']
})

But I got an error Maximum call stack size exceeded

What am I suppose to do

2 Answers

Actually, as I see, you are trying to make a tree data structure. TypeORM has some decorators for that. Here is an example:

import {
  Entity, BaseEntity, Column,
  PrimaryGeneratedColumn, Tree,
  TreeParent, TreeChildren
} from 'typeorm';

@Tree('materialized-path')
@Entity({ name: 'Menu' })
export class Category extends BaseEntity {
  @PrimaryGeneratedColumn({ type: 'int' })
  id: number;

  @Column({ type: 'varchar', length: 50 })
  text: string;

  // Check bellow
  @TreeParent()
  parent: Category;

  @TreeChildren()
  children: Category[];
}

The decorator @Tree() is used to tell to TypeORM that every Instance has self references for itself. Every item should have one parent, and should have several children. The ancestors and descendant can be setted with the decorators @TreeParent() and @TreeChildren() respectively. Check the documentation for more details about the different modes available for @Tree() decorator.

Since you have eager loading, each Category object is trying to load all its children eligible for categoryList. And since categoryList is also a list of Category entities, all it's children are also trying to load categoryList of their own. And this goes on and on until the stack is overflowed.

Remove eager loading from Category entity:

@Entity('categoryenter code here')
export class Category{
  @PrimaryGeneratedColumn({ type: 'int' })
  id: Category;

  @OneToMany(() => Category, category => category.category)
  categoryList: Category[];

  @ManyToOne(() => Category, (category) => category.categoryList)
  category: Category;
}
Related