DEV Community

Cover image for TypeORM Eager - Don't fall for it
Ram kumar Shrestha
Ram kumar Shrestha

Posted on

TypeORM Eager - Don't fall for it

Typeorm is very helpful tool when working with PostgreSQL. It has many built in features to help the developers. Among all of those features eager is one of them.

eager relations are loaded automatically each time you load entities from the database. For example, when Test is loaded the items table will be automatically joined and populated.

@Entity()
export class Test{
   @PrimaryGeneratedColumn('uuid')
   id: string;

   @OneToMany(() => TestItem, (item) => item.test, { eager: true })
   items: Array<TestItem>;
}
Enter fullscreen mode Exit fullscreen mode

It seems fun only if it is totally independent from other entities. But when the Test entity itself is joined to other entities then problem occurs.

Here are few downfall of using eager:

  1. Memory overload when the Test has too many items

  2. As earlier said if its joint in other tables/entities where items is not needed, then in that case we can not disable eager loading of items which is redundant.

  3. It always makes sures to load items or (eager loaded other relation) even for simple queries.

  4. Performance issue as the eager always loads all linked relations.

  5. Might cause maximum call stack memory exceeded error.

  6. Developers might forget the eager has been used and use extra relations on typeorm query or join table on query builder.

  7. Might go to infinite circular dependencies as below:

@Entity()
class TestItem {
   @ManyToOne(() => Test, (test) => test.items, { eager: true })
   test: Test;
}
Enter fullscreen mode Exit fullscreen mode

Here Test tries to eager load TestItem and vice versa which will cause circular dependencies.

Solution

Only load the relations whenever needed as:

  • Use relations with typeorm
await Test.find({ 
  relations: ['items']
});
Enter fullscreen mode Exit fullscreen mode
  • Use join with query builder
await Test.createQueryBuilder('test')
         .leftJoinAndSelect('test.items', 'items')
         .getMany();
Enter fullscreen mode Exit fullscreen mode

Have you ever used eager and forgot that you have used and just go with relations causing eventually the tragedy of performance loading???

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs