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
Step 1: Understand self-referencing ManyToMany
Users follow many users and are followed by many users, so a ManyToMany self-relation is needed.
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.
Final Answer:
Code snippet with @ManyToMany, inverse sides, and @JoinTable -> Option A
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 unknownstrongwhile earning +1 Grip toward your certificate.