TypeORM 0.3.11查询返回未选中列test问题求助
问题原因
你遇到的问题是因为实体类中test字段被直接赋值了默认值= true。TypeORM在将数据库查询结果映射到实体实例时,对于未在查询中选中的字段,会使用类定义里的默认值填充,哪怕数据库并没有返回该字段。虽然SQL日志显示只查询了name和id,但实体实例化时test字段会被自动设置为你定义的true,最终返回的JSON就包含了这个字段。
解决方案
以下几种方法可以解决这个问题:
1. 移除实体类中字段的直接赋值
只保留数据库层面的默认配置(@Column的default选项),去掉类属性的赋值:
export class Test extends BaseEntity { @PrimaryGeneratedColumn() id: number; @Column({ unique: true }) name: string; @Column('boolean', { default: true }) test: boolean; // 移除 = true @CreateDateColumn() createdAt: Date; @UpdateDateColumn() updatedAt: Date; }
这样,当查询未选中test字段时,实体实例中该字段会是undefined,序列化JSON时就不会包含它。
2. 设置字段默认不被选中
在@Column中添加select: false配置,让该字段默认不参与查询,只有显式指定时才会返回:
export class Test extends BaseEntity { @PrimaryGeneratedColumn() id: number; @Column({ unique: true }) name: string; @Column('boolean', { default: true, select: false }) test: boolean = true; @CreateDateColumn() createdAt: Date; @UpdateDateColumn() updatedAt: Date; }
这种方式可以保留类的默认值,但日常查询不会自动带出test字段,需要时在select中显式声明test: true才能获取。
3. 查询时返回原始数据
使用raw: true选项,让TypeORM直接返回数据库查询的原始结果,不映射为实体实例:
await testFind.find({ select: { name: true, }, raw: true })
返回的结果会是纯JSON对象,只包含SQL查询到的name和id字段。
内容的提问来源于stack exchange,提问作者ctappy
相关产品推荐
相关产品推荐

