Search code examples
javascriptexpressmany-to-manytypeormrelation

Update data many-to-many in typeorm express


i tried both .save and .update but it cause an error, --in the case of .save it return error: the value of a duplicate key breaks the unique constraint --in .update case it return error: the "userId" column of the "user" relation does not exist

note: i have 2 tables role and user and the association user_role

 //Many-to-many relation with user
  @ManyToMany((type) => User, (user) => user.roles)
  users: User[];



//Many-to-many relation with role
  @ManyToMany((type) => Role, {
    cascade: true,
  })
  @JoinTable({
    name: "users_roles",
    joinColumn: { name: "userId", referencedColumnName: "id" },
    inverseJoinColumn: { name: "roleId" }
  })
  roles: Role[];

the source code is : /* exemple of data entity2 = { username: 'user8', password: 'user8', firstname: 'test', lastname: 'tt', email: '[email protected]', company: 18, roles: [ { id: 62 }, { id: 63 } ] } */

  let entity = await this.userRepository.create(data.payload);

            let entity2 = { ...entity, roles: data.payload.selectedRoles }
    
 
            const user = await this.userRepository.save(entity2);
          /*const user = await this.userRepository.update(id, entity2);*/

            //todo we need to serialize the user
            // return only what we need like username , email, ...etc not password!!!!
            return { success: true, user: SanitizeUser(user) };

Solution

  • I did findone then .save, 1st get the data to update using data= this.userRepository.findOne(id) then you can apply userRepository.save(data) to this data. for example :

    const userUpdated = await this.userRepository.findOne(id)
          let dataUpdated = {
            ...userUpdated,
            username: data.payload.username,
            firstname: data.payload.firstname,
            lastname: data.payload.lastname,
            email: data.payload.email,
            company: data.payload.selectedCompany,
            roles: data.payload.selectedRoles
          }
    
          const user = await this.userRepository.save(dataUpdated);