Bird
Raised Fist0
NestJSframework~10 mins

Relations (OneToMany, ManyToOne, ManyToMany) in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Relations (OneToMany, ManyToOne, ManyToMany)
Define Entities
↓
Add Relation Decorators
↓
OneToMany <-> ManyToOne Setup
↓
ManyToMany Setup
↓
Use Repository to Save & Query
↓
Relations Loaded or Joined
↓
Access Related Data
This flow shows how to define entities, set up relations with decorators, save and query data, and access related entities in NestJS.
Execution Sample
NestJS
import { Entity, PrimaryGeneratedColumn, Column, OneToMany, ManyToOne } from 'typeorm';

@Entity()
export class Author {
  @PrimaryGeneratedColumn() id: number;
  @Column() name: string;
  @OneToMany(() => Book, book => book.author) books: Book[];
}

@Entity()
export class Book {
  @PrimaryGeneratedColumn() id: number;
  @Column() title: string;
  @ManyToOne(() => Author, author => author.books) author: Author;
}
Defines Author and Book entities with OneToMany and ManyToOne relations between them.
Execution Table
StepActionEntity StateRelation SetupResult
1Create Author instanceAuthor { id: undefined, name: 'Alice', books: [] }No relations yetAuthor object ready
2Create Book instanceBook { id: undefined, title: 'NestJS Guide', author: undefined }No relations yetBook object ready
3Assign author to bookBook.author = Author instanceManyToOne relation setBook linked to Author
4Add book to author's books arrayAuthor.books = [Book instance]OneToMany relation setAuthor linked to Book
5Save Author and Book to DBEntities persistedRelations saved via foreign keysData stored with relations
6Query Book with author relationBook loaded with authorRelation joinedBook.author accessible
7Query Author with books relationAuthor loaded with books arrayRelation joinedAuthor.books accessible
8Exit--Relations fully established and accessible
💡 All entities saved and relations correctly linked in database
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
Author instanceundefined{ id: undefined, name: 'Alice', books: [] }{ id: undefined, name: 'Alice', books: [] }{ id: undefined, name: 'Alice', books: [] }{ id: undefined, name: 'Alice', books: [Book instance] }Persisted with id
Book instanceundefinedundefined{ id: undefined, title: 'NestJS Guide', author: undefined }{ id: undefined, title: 'NestJS Guide', author: Author instance }{ id: undefined, title: 'NestJS Guide', author: Author instance }Persisted with id
Key Moments - 3 Insights
Why do we assign the author to the book and also add the book to the author's books array?
Because OneToMany and ManyToOne relations are two sides of the same link. Assigning both ensures the relation is complete in memory before saving, as shown in steps 3 and 4 of the execution_table.
What happens if we save only the book without adding it to the author's books array?
The database will store the foreign key from book to author, but the author's books array in memory won't reflect the relation until reloaded, as the OneToMany side is not updated (see step 4).
How does ManyToMany differ from OneToMany/ManyToOne in setup?
ManyToMany uses a join table to link entities on both sides equally, unlike OneToMany/ManyToOne which uses a foreign key on the ManyToOne side. This is a separate step after OneToMany/ManyToOne setup.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what relation is being set?
AOneToMany from Author to Book
BManyToOne from Book to Author
CManyToMany between Author and Book
DNo relation set yet
💡 Hint
Check the 'Relation Setup' column at step 3 in execution_table
At which step does the Author's books array get updated?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look for 'Author.books = [Book instance]' in the 'Entity State' column
If we skip adding the book to the author's books array, what will happen?
AThe relation will be fully saved and accessible both ways
BThe book will not save at all
CThe database will save the relation but Author.books in memory will be empty
DAn error will occur during save
💡 Hint
Refer to key_moments explanation about incomplete relation setup
Concept Snapshot
Relations in NestJS with TypeORM:
- Use @OneToMany on the 'one' side and @ManyToOne on the 'many' side
- Both sides must reference each other for full relation
- ManyToMany uses @ManyToMany with a join table
- Save entities with relations to persist foreign keys
- Query with relations to access linked data easily
Full Transcript
This visual execution trace shows how to set up relations in NestJS using TypeORM decorators. First, entities are defined with @Entity and columns. Then, relations are added using @OneToMany and @ManyToOne decorators referencing each other. Instances of entities are created and linked by assigning the related objects on both sides. Saving these entities persists the relations in the database via foreign keys. Querying with relations loads the linked data for easy access. Key moments clarify why both sides must be assigned and how ManyToMany differs. The quiz tests understanding of relation setup steps and effects of incomplete linking.

Practice

(1/5)
1. In NestJS using TypeORM, which decorator correctly defines a OneToMany relationship from an Author entity to a Book entity?
easy
A. @OneToMany(() => Book, book => book.author)
B. @ManyToOne(() => Book, book => book.author)
C. @ManyToMany(() => Book, book => book.author)
D. @OneToOne(() => Book, book => book.author)

Solution

  1. Step 1: Understand the relationship direction

    A OneToMany relationship means one Author has many Books.
  2. Step 2: Identify the correct decorator syntax

    The decorator @OneToMany(() => Book, book => book.author) correctly sets this relation from Author to Book.
  3. Final Answer:

    @OneToMany(() => Book, book => book.author) -> Option A
  4. Quick Check:

    OneToMany from Author to Book = @OneToMany [OK]
Hint: OneToMany decorator links one entity to many others [OK]
Common Mistakes:
  • Confusing OneToMany with ManyToOne
  • Using ManyToMany instead of OneToMany
  • Incorrect arrow function syntax in decorator
2. Which of the following is the correct syntax to define a ManyToOne relation in a NestJS entity?
easy
A. @OneToOne(type => User, user => user.posts)
B. @OneToMany(type => User, user => user.posts)
C. @ManyToOne(type => User, user => user.posts)
D. @ManyToMany(type => User, user => user.posts)

Solution

  1. Step 1: Recognize the relation type

    ManyToOne means many posts belong to one user.
  2. Step 2: Confirm correct decorator syntax

    @ManyToOne(type => User, user => user.posts) is the correct way to define this relation.
  3. Final Answer:

    @ManyToOne(type => User, user => user.posts) -> Option C
  4. Quick Check:

    ManyToOne relation uses @ManyToOne decorator [OK]
Hint: ManyToOne decorator links many items to one parent [OK]
Common Mistakes:
  • Using OneToMany instead of ManyToOne
  • Wrong arrow function parameter name
  • Missing inverse side property
3. Given these entity relations in NestJS with TypeORM:
class Student {
  @ManyToMany(() => Course, course => course.students)
  courses: Course[];
}

class Course {
  @ManyToMany(() => Student, student => student.courses)
  @JoinTable()
  students: Student[];
}

What will be the result of fetching a Course with its students included?
medium
A. A Course object with a single Student object in the 'students' property
B. A Course object with an array of Student objects in the 'students' property
C. A Course object without any students because @JoinTable is missing
D. An error because ManyToMany requires OneToMany on one side

Solution

  1. Step 1: Understand ManyToMany relation with JoinTable

    ManyToMany with @JoinTable on one side creates a join table linking many students to many courses.
  2. Step 2: Fetching Course includes students array

    Fetching a Course with relations loaded returns a Course object with an array of Student objects in 'students'.
  3. Final Answer:

    A Course object with an array of Student objects in the 'students' property -> Option B
  4. Quick Check:

    ManyToMany with @JoinTable returns array of related entities [OK]
Hint: ManyToMany with @JoinTable returns arrays on both sides [OK]
Common Mistakes:
  • Expecting single object instead of array
  • Forgetting @JoinTable on one side
  • Confusing ManyToMany with OneToMany
4. Consider this NestJS entity code snippet:
@Entity()
class Post {
  @OneToMany(() => Comment, comment => comment.post)
  comments: Comment[];
}

@Entity()
class Comment {
  @ManyToOne(() => Post, post => post.comments)
  post: Post;
}

What is wrong if the comments property in Post is not initialized as an array?
medium
A. No issue; undefined is acceptable for relations
B. TypeORM will automatically initialize it as an empty array
C. The database schema will not be created
D. It will cause runtime errors when accessing or pushing comments

Solution

  1. Step 1: Recognize relation property type

    comments is an array of Comment entities, so it should be initialized to avoid undefined.
  2. Step 2: Understand runtime behavior

    If not initialized, accessing or pushing to comments causes runtime errors like 'cannot read property push of undefined'.
  3. Final Answer:

    It will cause runtime errors when accessing or pushing comments -> Option D
  4. Quick Check:

    Uninitialized array relation causes runtime errors [OK]
Hint: Always initialize OneToMany arrays to avoid runtime errors [OK]
Common Mistakes:
  • Assuming TypeORM auto-initializes arrays
  • Ignoring runtime errors from undefined arrays
  • Confusing property initialization with database schema
5. You want to model a social media app where users can follow many other users and be followed by many users. Which NestJS TypeORM relation setup correctly models this ManyToMany self-referencing relation?
hard
A.
@Entity()
class User {
  @ManyToMany(() => User, user => user.followers)
  @JoinTable()
  following: User[];

  @ManyToMany(() => User, user => user.following)
  followers: User[];
}
B.
@Entity()
class User {
  @OneToMany(() => User, user => user.followers)
  following: User[];

  @ManyToOne(() => User, user => user.following)
  followers: User[];
}
C.
@Entity()
class User {
  @ManyToOne(() => User, user => user.followers)
  following: User[];

  @OneToMany(() => User, user => user.following)
  followers: User[];
}
D.
@Entity()
class User {
  @ManyToMany(() => User)
  @JoinTable()
  following: User[];

  @ManyToMany(() => User)
  followers: User[];
}

Solution

  1. Step 1: Understand self-referencing ManyToMany

    Users follow many users and are followed by many users, so a ManyToMany self-relation is needed.
  2. Step 2: Correctly set inverse sides and JoinTable

    @Entity()
    class User {
      @ManyToMany(() => User, user => user.followers)
      @JoinTable()
      following: User[];
    
      @ManyToMany(() => User, user => user.following)
      followers: User[];
    }
    uses @ManyToMany with inverse sides and @JoinTable on one side, correctly modeling the relation.
  3. Final Answer:

    Code snippet with @ManyToMany, inverse sides, and @JoinTable -> Option A
  4. Quick Check:

    Self-referencing ManyToMany needs inverse sides and one @JoinTable [OK]
Hint: Self ManyToMany needs inverse sides and one @JoinTable [OK]
Common Mistakes:
  • Using OneToMany or ManyToOne for many-to-many
  • Missing inverse side property
  • Missing @JoinTable on one side
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard