I want to establish a one-to-one relationship between User and Profile. In this relationship, User is the owner, meaning that a user has a profile. However, when I execute the code, I encounter the following error message:
{ name: 'Greg', password: '123', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="deb9acbbb99eb6bbacbbf0bdb1b3">[email protected]</a>' }
MustBeEntityError: Cannot save, given value must be an entity, instead "undefined" is given.
The issue arises because postman expects user.profile to be defined, but since I am developing a SPA with React on the frontend, the profile does not exist at the time of user signup. To address this problem, I consider setting a default value for the profile when calling the route to create the user. Later, I can create the profile separately and update it for the user using another route.
This is my implementation in User.ts:
@Entity("User")
export class User extends BaseEntity {
@Column("number")
@PrimaryGeneratedColumn()
id: number;
@Column("text")
name: string;
@Column("text")
password: string;
@Column("text")
email: string;
// https://stackoverflow.com/questions/62460079/typeorm-foreign-key-not-showing-on-a-
find-call
@Column("number", { default: -1, name: "profileId" })
profileId: number;
@OneToOne(() => Profile, { cascade: true })
@JoinColumn({ name: "profileId" })
profile: Profile;
}
And here is my approach in Profile.ts:
@Entity("Profile")
export class Profile extends BaseEntity {
@Column("number")
@PrimaryGeneratedColumn()
id: number;
@Column("text", { nullable: true })
gender: string;
@Column("text", { nullable: true })
occupation: string;
@OneToOne(() => User, (user) => user.profile) // specify inverse side as a second parameter
user: User;
}