I have an entity Store that stores in itself
@Entity('shops')
export class ShopEntity{
@PrimaryGeneratedColumn()
id: number;
@OneToOne(() => ScheduleEntity)
@JoinColumn()
schedule: ScheduleEntity;
}
I also have a Schedule entity
@Entity('schedules')
export class ScheduleEntity {
@PrimaryGeneratedColumn()
id: number;
@Column('jsonb')
monday: DayDto;
}
In the shop entity, I insert such an ordinary thing
@AfterInsert()
async createDefaultSchedule() {
const schedule = new ScheduleEntity();
const initialDay: DayDto = {
bags: 0,
enabled: true,
timeEnd: '16:00',
timeStart: '15:00',
};
schedule.monday = initialDay;
const scheduleRepo = await Data.getRepository(ScheduleEntity);
scheduleRepo.save(schedule);
}
But when creating a shop, I get an error: EntityMetadataNotFoundError: No metadata for "ScheduleEntity" was found.
I don’t even know if it’s possible to do it this way, because there are slight doubts about it, so that when creating an entity, I would create another entity in the relationship
Just like @nbk mentioned your shops
table has a one-to-one relationship with schedules
table.
Based on your entity definition, a ShopEntity
cannot exist without creating its related ScheduleEntity
because ShopEntity
has the foreign key constraint (@JoinColumn()
decorator defines which entity is going to save the foreign key).
To fix this specific issue, you can modify your entities like this:
@Entity('shops')
export class ShopEntity{
@PrimaryGeneratedColumn()
id: number;
// Remove `@JoinColumn()` decorator from this entity.
@OneToOne(() => ScheduleEntity, (schedule) => schedule.shop)
schedule: ScheduleEntity;
}
@Entity('schedules')
export class ScheduleEntity {
@PrimaryGeneratedColumn()
id: number;
@Column('jsonb')
monday: DayDto;
// Add `@JoinColumn()` decorator to this entity.
@OneToOne(() => ShopEntity, (shop) => shop.schedule)
@JoinColumn()
shop: ShopEntity
}
Now your ShopEntity
can exist without first having a ScheduleEntity
.
However, I believe you don't need to use @AfterInsert
at all here. You can simply save both entities at once like below:
await shopRepo.save({
id: 'shopID',
// Simply add the properties of `ScheduleEntity` inside `ShopEntity`
// like this (don't add an `id` for `ScheduleEntity` since it will
// be done by TypeORM automatically).
schedule: {
monday: {
bags: 0,
enabled: true,
timeEnd: '16:00',
timeStart: '15:00',
},
},
});