How to fix 'TypeError: relatedEntities.forEach is not a function' from typeorm

How to fix 'TypeError: relatedEntities.forEach is not a function' from typeorm

我正在使用 TypeORM + PostgreSQL 设置服务器。将我的实体保存到实体存储库时,我收到错误:TypeError: relatedEntities.forEach is not a function 并且实体未保存到数据库。

这似乎只有在我使用 @OneToMany@TreeChildren 装饰器时才会发生。

这是导致问题的实体 class:

import { ServiceData } from './service-data.entity';
import { ManufacturerData } from './manufacturer-data.entity';
import { Entity, Column, PrimaryGeneratedColumn, TreeChildren } from 'typeorm';

@Entity()
export class Advertisement {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ nullable: true })
  name?: string;

  @Column()
  gatewayId: string;

  @Column()
  rssi: number;

  @Column({ nullable: true })
  mac?: string;

  @TreeChildren()
  manufacturerData?: ManufacturerData[];

  @TreeChildren()
  serviceData?: ServiceData;
}

(缩写)错误输出为:

UnhandledPromiseRejectionWarning: TypeError: relatedEntities.forEach is not a function
    at OneToManySubjectBuilder.buildForSubjectRelation (/<project-directory>/src/persistence/subject-builder/OneToManySubjectBuilder.ts:78:25)

找到问题了。

@TreeChildren@OneToMany 总是需要一个数组。我不得不将 serviceData?: ServiceData; 更改为 serviceData?: ServiceData[];