NestJSData with an ORMLesson 47 / 69

Queries & relations

Code Lab45 min

Queries & relations

Relations load connected data in one query:

this.repo.find({
  where: { slug },
  relations: { courses: { chapters: { lessons: true } } },
  order: { courses: { position: 'ASC' } },
});

That is the exact query behind this app's roadmap pages: one ask, the whole tree, in order. The alternative — a query per level — is the N+1 problem, and it is how servers die quietly.

Filter with where, sort with order, connect with relations. Three words carry almost every query you will write.

Exercise

Write the repository call that loads one course with its chapters and lessons, lessons ordered by position.

Practice this lesson in the IDE

Open the NestJS practice workspace, edit the starter code, and run your work in the browser.

Open IDE and practice