You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeORM查询嵌入式实体列时出现Cannot read properties of undefined报错

TypeORM嵌入式实体查询报错:Cannot read properties of undefined (reading 'dateDebut')

问题场景

使用Node.js、TypeScript、TypeORM和PostgreSQL开发时,实现并查询TypeORM嵌入式实体遇到错误。

主实体类中的嵌入式属性:

@Column(() => Periode)
readonly periode: Periode;

嵌入式实体Periode类定义:

export class Periode implements IPeriode {
  @Column()
  readonly dateDebut: Date;

  @Column()
  readonly dateFin?: Date;
}

编写的查询方法:

async findByDate(date: Date): Promise<Exercice | undefined> {
  const found = await this.model.findOne({
    relations: {
      periode: true,
    },
    where: { periode: { dateDebut: LessThanOrEqual(date), dateFin: MoreThanOrEqual(date) } },
  });

  return found || undefined;
}

调用该方法时出现错误:

"Cannot read properties of undefined (reading 'dateDebut')"

错误原因

嵌入式实体不是关系型关联实体,它是直接嵌入到主实体的数据库表中,字段会以类似periode_dateDebut、periode_dateFin的形式存在于主表内。而relations选项是用于加载**关联实体(如一对一、一对多关系)**的,对嵌入式实体使用该选项会导致TypeORM错误地尝试将其当作关联实体处理,进而找不到对应的关联数据,最终抛出periode为undefined的报错。

解决方法

移除查询配置中的relations选项即可,修正后的查询方法如下:

async findByDate(date: Date): Promise<Exercice | undefined> {
  const found = await this.model.findOne({
    where: { periode: { dateDebut: LessThanOrEqual(date), dateFin: MoreThanOrEqual(date) } },
  });

  return found || undefined;
}

注:嵌入式实体的嵌套查询写法是正确的,TypeORM会自动将其映射到对应的表字段上。

内容的提问来源于stack exchange,提问作者Sabgramar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 13:50:25