Bird
Raised Fist0
NestJSframework~20 mins

Relations (OneToMany, ManyToOne, ManyToMany) in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Relations Mastery in NestJS
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this NestJS entity relation setup?

Given these two entities in NestJS using TypeORM, what will be the result of fetching a Post with its comments?

NestJS
import { Entity, PrimaryGeneratedColumn, Column, OneToMany, ManyToOne } from 'typeorm';

@Entity()
export class Post {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  title: string;

  @OneToMany(() => Comment, comment => comment.post)
  comments: Comment[];
}

@Entity()
export class Comment {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  text: string;

  @ManyToOne(() => Post, post => post.comments)
  post: Post;
}

// Assume a Post with id=1 has 3 comments linked.
// What will be the value of post.comments after fetching Post with id=1 including relations?
AUndefined, because OneToMany does not load relations automatically
BAn empty array because relations are not set up correctly
CA single Comment object instead of an array
DAn array of 3 Comment objects linked to the Post
Attempts:
2 left
💡 Hint

Remember that OneToMany defines a collection of related entities.

📝 Syntax
intermediate
2:00remaining
Which option correctly defines a ManyToMany relation in NestJS with TypeORM?

Choose the correct syntax to define a ManyToMany relation between User and Role entities with a join table.

A
@ManyToMany(Role)
@JoinTable
roles: Role[];
B
@ManyToMany(() => Role, role => role.users)
@JoinTable()
roles: Role[];
C
@ManyToMany(() => Role, role => role.users)
roles: Role[];
D
@ManyToMany(() => Role)
@JoinTable()
roles: Role[];
Attempts:
2 left
💡 Hint

Remember to use a function returning the class and to add @JoinTable() on one side.

🔧 Debug
advanced
2:00remaining
Why does this ManyToOne relation cause a runtime error?

Consider this entity code snippet:

import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from 'typeorm';
import { Category } from './category.entity';

@Entity()
export class Product {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @ManyToOne(Category)
  category: Category;
}

When running the app, it throws an error about missing function in relation definition. What is the cause?

AThe @Column decorator is missing on the category property
BThe Category entity is missing a primary key
CThe relation decorator should use a function returning the class: @ManyToOne(() => Category)
DThe Product entity must import Category with a relative path
Attempts:
2 left
💡 Hint

Check how the relation decorator references the related class.

❓ state_output
advanced
2:00remaining
What is the state of the database after saving these entities with ManyToMany relation?

Given these entities and code:

import { Entity, PrimaryGeneratedColumn, Column, ManyToMany, JoinTable } from 'typeorm';

@Entity()
export class Student {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @ManyToMany(() => Course, course => course.students)
  @JoinTable()
  courses: Course[];
}

@Entity()
export class Course {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  title: string;

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

// Code snippet:
const student = new Student();
student.name = 'Alice';

const course1 = new Course();
course1.title = 'Math';

const course2 = new Course();
course2.title = 'Science';

student.courses = [course1, course2];

await studentRepository.save(student);

What will be saved in the database?

AOnly the student 'Alice' is saved; courses are not saved automatically
BStudent 'Alice' saved with two new courses 'Math' and 'Science' and join table entries linking them
CCourses are saved but the join table linking student and courses is empty
DAn error occurs because courses are not saved before assigning
Attempts:
2 left
💡 Hint

TypeORM does not cascade saves by default for relations.

🧠 Conceptual
expert
3:00remaining
Which statement best describes the difference between OneToMany and ManyToOne in NestJS TypeORM?

Choose the most accurate explanation of how OneToMany and ManyToOne decorators relate entities in NestJS with TypeORM.

A<code>ManyToOne</code> defines the owning side and stores the foreign key column, while <code>OneToMany</code> is inverse and does not store the key.
B<code>OneToMany</code> and <code>ManyToOne</code> are interchangeable and both store foreign keys.
CBoth <code>OneToMany</code> and <code>ManyToOne</code> store foreign keys independently in their tables.
D<code>OneToMany</code> defines the owning side of the relation and stores the foreign key, while <code>ManyToOne</code> is inverse and does not store the key.
Attempts:
2 left
💡 Hint

Think about which side owns the foreign key column in the database.

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