运行TypeORM多对一/一对多代码遇DataTypeNotSupportedError求解决
报错原因
出现DataTypeNotSupportedError: Data type "Object" in "Photo.user" is not supported by "postgres" database错误的核心原因是:TypeORM未将Photo.user识别为关联字段,而是将其当作普通Object类型列处理,但PostgreSQL不支持Object原生数据类型。
通常由以下场景导致:
Photo实体中user字段的@ManyToOne装饰器配置错误,比如漏写关联的目标实体类,或箭头函数返回值不正确- 实体类未被正确注册到TypeORM的数据源配置中
- 双向关联的
@OneToMany配置不匹配,导致TypeORM无法解析关联关系
修复方案
1. 修正Photo实体的@ManyToOne关联配置
确保@ManyToOne装饰器正确指定关联的User实体,同时配置反向关联字段:
import { Entity, Column, ManyToOne, PrimaryGeneratedColumn } from "typeorm"; import { User } from "./User"; @Entity() export class Photo { @PrimaryGeneratedColumn() id: number; @Column() url: string; // 正确配置ManyToOne关联,指向User实体并关联其photos字段 @ManyToOne(() => User, user => user.photos) user: User; }
2. 同步User实体的@OneToMany配置
确保User实体的@OneToMany装饰器与Photo的@ManyToOne形成双向关联:
import { Entity, Column, OneToMany, PrimaryGeneratedColumn } from "typeorm"; import { Photo } from "./Photo"; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; // 正确配置OneToMany关联,指向Photo实体的user字段 @OneToMany(() => Photo, photo => photo.user) photos: Photo[]; }
3. 确认实体已注册到数据源
检查TypeORM数据源配置文件(通常为data-source.ts),确保entities数组包含User和Photo实体:
import { DataSource } from "typeorm"; import { User } from "./entity/User"; import { Photo } from "./entity/Photo"; export const AppDataSource = new DataSource({ type: "postgres", host: "localhost", port: 5432, username: "postgres", password: "password", database: "test", entities: [User, Photo], // 必须包含两个实体 synchronize: true, logging: false, });
4. 验证TypeORM版本兼容性
若使用的TypeORM版本过旧,可能存在装饰器语法差异,建议升级到与官方文档匹配的稳定版本(如最新0.3.x系列)。
内容的提问来源于stack exchange,提问作者U. Watt
相关产品推荐
相关产品推荐

