Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

673
Views
Whats the best way to save Many to Many relationships using TypeORM and NestJS?

So I have two entities, User and Role with Many-To-Many relationship between them.

user.entity.ts

@Entity()
@ObjectType()
export class User {
  @PrimaryGeneratedColumn('uuid')
  @Field(() => String)
  id: string;

  @Field(() => String)
  @Column()
  name!: string;

  @Field(() => [Role])
  @ManyToMany(() => Role, (role) => role.users, {
    cascade: true,
    lazy: true,
  })
  @JoinTable()
  roles!: Array<Role>;
}
// Deleting the unnecessary properties for readability


role.entity.ts

@Entity()
@ObjectType()
export class Role {
  @PrimaryGeneratedColumn('uuid')
  @Field(() => String)
  id: string;

  @Field(() => String)
  @Column()
  name!: string;

  @Field(() => [User])
  @ManyToMany(() => User, (user) => user.roles, {
    lazy: true,
  })
  users: Promise<Array<User>>;

  @Field(() => String)
  @CreateDateColumn()
  createdAt: Date;
}

The problem I am facing is that when I have to create a new User, I have to first extract the role ids from the DTO, fetch for each ID the role object in the database and then wire it to the user object manually before saving.

const {roleIds} = createUserInput;
const roles = roleIds.map(async (id) => await roleService.findById(id))
const user = this.userRepository.create({...createUserInput, roles});
return this.userRepository.save(user);

And this is all working fine, but I just am curious if there is a way to get this to work without making the extra calls and manual wiring. If I can just pass in the roleIds and it magically auto resolves it. Something like this:

const user = this.userRepository.create({...createUserInput, roleIds});
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!