Attempting to use both .save and .update is causing errors. When using .save, it returns an error stating: the value of a duplicate key breaks the unique constraint. On the other hand, when using .update, it returns an error saying: the "userId" column of the "user" relation does not exist.
It should be noted that there are 2 tables involved - 'role' and 'user', with an association called 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 snippet provided includes:
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) };