javascriptnode.jsnestjstypeorm

TypeORM results to undefined on OneToOne relationship


I'm new to NestJS (I had a bit of experience in Angular). I'm tasked to create a new microservice. I'm getting undefined when I console.log a JoinTable (the tables are new).

So Unit and Hub has One to One relationship.

Here is the unit

  @Entity({
    name: 'units',
  })
  export class UnitEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @OneToOne(() => HubEntity)
    @JoinColumn({name: "hub_id"})
    hub: HubEntity;

I also tried coding it like this:

    @OneToOne(type => HubEntity, hub => hub.unit)
    @JoinColumn({name: "hub_id"})
    hub: HubEntity;

For the HUB:

 @Entity({
    name: 'hubs',
  })
  export class HubEntity {
    @PrimaryGeneratedColumn()
    id: number;
  
    @OneToOne(type => UnitEntity, unit => unit.hub)
    @JoinColumn({name: "hub_id"})
    unit: UnitEntity;

For testing, this is how I consoled it.

async findAllByUnit(unitId: number) {
    const unit = await this.unitRepository.findOne(unitId)

    console.log(unit.hub)
  }

It returns undefined. What am I missing?


Solution

  • You have to include the relationship like this:

    await this.unitRepository.findOne(unitId, {
        relations: ['hub']
    })