I'm using NestJS 10 with TypeORM 0.3.17. I have defined this entity wiht a @OneToOne relationship
@Entity()
export class User {
@PrimaryGeneratedColumn('uuid')
id: string;
...
@Column()
password: string;
@OneToOne(() => Contact, {
cascade: true,
onDelete: 'CASCADE',
nullable: true,
})
@JoinColumn({ name: 'contact_id', referencedColumnName: 'id' })
contact?: Contact;
}
I have defined a corresponding UpdateUserDto and CreateUserDto ...
export class UpdateUserDto extends PartialType(CreateUserDto) {
}
export class CreateUserDto {
email: string;
password: string;
refreshToken: string;
contact: CreateContactDto;
}
How do I create a service method to update a single field from my Contact object? I tried this
export class UsersService {
constructor(
private readonly userRepository: UserRepository, // import as usual
) {}
...
async update(
id: string,
updateUserDto: UpdateUserDto,
): Promise<UpdateResult> {
return this.userRepository.update(id, updateUserDto);
}
but when I call this method with the parameters
this.usersService.update(userId, {
contact: {
firstName: 'Dave',
lastName: 'Test',
mailingAddress: {
addressLine1: '321 oklahoma',
city: 'Springfield',
zipCode: '90210',
region: { id: '123' }
}
}
});
It fails with the runtime error
[ExceptionsHandler] Property "contact.firstName" was not found in "User". Make sure your query is correct.
Edit: Adding contact entity ...
import { Address } from 'src/addresses/entities/address.entity';
import { User } from 'src/users/entities/user.entity';
import {
Column,
Entity,
JoinColumn,
ManyToOne,
OneToOne,
PrimaryGeneratedColumn,
} from 'typeorm';
@Entity()
export class Contact {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
firstName: string;
@Column()
lastName: string;
...
@OneToOne((type) => Address, {
cascade: true,
onDelete: 'CASCADE',
})
@JoinColumn({ name: 'mailing_address_id', referencedColumnName: 'id' })
mailingAddress: Address;
}
First of all, find the user by ID:
Then create Contact Object;
And finally, you can save the relation :