Search code examples
mysqltypescripttypeormnode.js-typeorm

EntityPropertyNotFoundError Typeorm Relations Find


Motivation

I have an error using Typeorm load relations with find otions.
The code is similar to the example in Typeorm documentation but seems not to work.

Typeorm repository find with relation options

await this.userRepository.findOneOrFail({
  where: { id },
  relations: { 
    cursos: { 
      nome: true 
    }
  },
});

Relations

  • Users
@Entity({ name: 'users' })
export class Users {
  @PrimaryGeneratedColumn()
  id: number;

  @Columns()
  nome: string;

  @OneToMany(() => Courses, (course) => course.user)
  cursos: Courses[];
}
  • Courses
@Entity({ name: 'cursos' })
export class Courses {
  @PrimaryColumn({ nullable: false })
  id: number;

  @Column()
  nome: string;

  @Column()
  user_id: number;

  @ManyToOne(() => Users, (user) => user.cursos)
  @JoinColumn({ name: 'user_id', referencedColumnName: 'id' })
  user: Users;
}

Expected

{
  "id": 1,
  "nome": "Rogerio",
  "cursos": [
    {
      "nome": "BACHARELADO EM ENG DE COMPUTAÇÃO"
    }
  ]
}

Error

[ExceptionsHandler] Property "nome" was not found in "Courses". Make sure your query is correct.
EntityPropertyNotFoundError: Property "nome" was not found in "Courses". Make sure your query is correct.

Solution

  • I just figured out how to get around this problem, using the select option outside the relation

    await this.userRepository.findOneOrFail({
      where: { id },
      relations: { cursos: true },
      select: { cursos: { id: true, nome: true }
    });