I have a rather simple entity model where a user has basic information. If a user also has a provider function a OneToOne relation will be created to the provider table.
My issue is that if I update a user without any provider function it works as expected. The fields which changed get updated but no new entry gets created. If the user has a provider function, all fields of the user get updated and no new entry gets created. In the table of the provider information each updated creates a new entry and the new ID gets set in the user table.
@Entity()
export class Users {
@Column('text', {primary: true})
uid: string;
@Column('text', {nullable: true})
firstName: string;
@Column('text', {nullable: true})
lastName: string;
@Column('text')
email: string;
@Column('text')
password: string;
@Column('text', {nullable: true})
role: string;
@OneToOne(type => Providers, providerData => providerData.user, {cascade: true})
@JoinColumn()
providerData: Providers;
@OneToOne(type => Clients, clientData => clientData.user, {cascade: true})
@JoinColumn()
clientData: Clients;
@Column('bytea', {nullable: true})
photo: Uint8Array;
}
Update function:
async update(uid: string, dto: UpdateUserDto): Promise<Users> {
const userToUpdate = await this.usersRepository.findOne(uid);
try {
const user = new Users();
const provider = new Providers();
const client = new Clients();
user.email = dto.email;
user.firstName = dto.firstName;
user.lastName = dto.lastName;
user.photo = dto.photo;
user.role = dto.role;
Logger.log(dto.email);
provider.licensed = dto.licensed;
provider.notes = dto.notes;
provider.paymentOptions = dto.paymentOptions;
provider.speciality = dto.speciality;
user.providerData = provider;
user.clientData = client;
const updatedUser: Users = Object.assign(user, dto);
updatedUser.uid = uid;
Logger.log('Updated User with UID: ' + userToUpdate.uid);
return await this.usersRepository.save(updatedUser);
} catch (error) {
Logger.log('Error updating user: ' + error);
}
}
What am I doing wrong or what is a better solution?
You are creating a new user instead of updating the existing one. try to add this line
const editedUser = this.usersRepository.merge(userToUpdate ,updatedUser);
and then save it
return this.usersRepository.save(editedUser);