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

TypeORM报错EntityMetadataNotFound:Product元数据缺失怎么解决?

问题

我使用Express框架结合TypeORM开发应用,已按如下方式配置DataSource的entities:

export const dataSourceInstance = () =>  {
 return new DataSource({
    type: 'postgres',
    host: process.env.PG_HOST,
    port: Number(process.env.PG_PORT),
    username: process.env.PG_USERNAME,
    password: process.env.PG_PASSWORD,
    database: process.env.PG_DATABASE,
    entities: [Product, Orders, Customers],
    synchronize: true
 })
}

实体类定义如下:

@Entity('customers')
export class Customers extends BaseEntity {

@PrimaryGeneratedColumn()
id: number;

@Column({
    nullable: true,
    length: 100
})
fullName: string;

@Column()
age: number;

@Column()
country: number;

@Column({
    nullable: false
})
city: number;

@Column({
    nullable: false
})
contactNumber: string;

@OneToMany(() => Orders, (order) => order.customers)
orders: Orders[]

@CreateDateColumn()
created_at: Date

@UpdateDateColumn()
updated_at: Date
}


@Entity('orders')
export class Orders extends BaseEntity {

@PrimaryGeneratedColumn()
id: number;

@OneToOne(() => Product)
@JoinColumn()
product: Product

@Column({
    length: 500
})
description: string;

@Column({
    nullable: false
})
quantity: number;

@Column({
    nullable: false
})
amount: number;

@Column({
    nullable: false
})
paymentMethod: string;

@Column()
weight: string;

@Column()
customizeName: string;

@ManyToOne(() => Customers, (customer) => customer.orders)
customers: Customers

@ManyToMany(() => Product)
@JoinTable()
products: Product[]

@CreateDateColumn()
created_at: Date
}

@Entity('product')
export class Product extends BaseEntity {

@PrimaryGeneratedColumn()
id: number;

@Column({
    unique: true,
    length: 200,
    nullable: false
})
name: string;

@Column()
description: string;

@Column({
    nullable: false
})
cost: number;

@Column({
    nullable: false
})
price: number;

@Column()
weight: string;

@CreateDateColumn()
created_at: Date
}

入口文件app.ts的初始化逻辑如下:

const app = express()

app.use(morgan('dev'))
app.use('/api/v1', routes)

app.listen(PORT, async() => {
 try {
    console.log(`Server is running on PORT: ${PORT}`)
    await dataSourceInstance().initialize()
    console.info('connected to the database')
 } catch (err) {
    console.error("Error in starting the server: ", err)
 }
})

我已在服务器启动时初始化数据源,且entities数组中包含Product、Orders、Customers,但保存Product实体记录时仍报错:

No metadata for "Product" was found.

完整错误栈:

EntityMetadataNotFoundError: No metadata for "Product" was found.
at DataSource.getMetadata (/Users/fahadsubzwari924/Documents/sideProjects/cwc/server/node_modules/src/data-source/DataSource.ts:427:30)
at Repository.get metadata [as metadata] (/Users/fahadsubzwari924/Documents/sideProjects/cwc/server/node_modules/src/repository/Repository.ts:52:40)
at Repository.save (/Users/fahadsubzwari924/Documents/sideProjects/cwc/server/node_modules/src/repository/Repository.ts:205:18)
at ProductService.<anonymous> (/Users/fahadsubzwari924/Documents/sideProjects/cwc/server/src/services/product.ts:8:52)
at Generator.next (<anonymous>)
at /Users/fahadsubzwari924/Documents/sideProjects/cwc/server/src/services/product.ts:8:71
at new Promise (<anonymous>)
at __awaiter (/Users/fahadsubzwari924/Documents/sideProjects/cwc/server/src/services/product.ts:4:12)
at ProductService.createProduct (/Users/fahadsubzwari924/Documents/sideProjects/cwc/server/src/services/product.ts:7:55)
at ProductController.<anonymous> (/Users/fahadsubzwari924/Documents/sideProjects/cwc/server/src/controllers/product.controller.ts:11:50)
POST /api/v1/products 500 15.061 ms - 97

解决方案

1. 修复DataSource单例问题

当前每次调用dataSourceInstance()都会创建新的DataSource实例,而服务层使用的Repository可能来自未初始化的实例。改成单例模式:

// 定义全局单例数据源
let dataSource: DataSource | null = null;

export const getDataSourceInstance = async () => {
  if (!dataSource) {
    dataSource = new DataSource({
      type: 'postgres',
      host: process.env.PG_HOST,
      port: Number(process.env.PG_PORT),
      username: process.env.PG_USERNAME,
      password: process.env.PG_PASSWORD,
      database: process.env.PG_DATABASE,
      entities: [Product, Orders, Customers],
      synchronize: true
    });
    await dataSource.initialize();
  }
  return dataSource;
};

在app.ts中初始化:

app.listen(PORT, async() => {
 try {
    console.log(`Server is running on PORT: ${PORT}`)
    await getDataSourceInstance();
    console.info('connected to the database')
 } catch (err) {
    console.error("Error in starting the server: ", err)
 }
})

服务层获取Repository时必须从该单例实例获取:

// ProductService.ts
const dataSource = await getDataSourceInstance();
const productRepo = dataSource.getRepository(Product);
await productRepo.save(productData);

2. 检查实体导入与装饰器

  • 确认在DataSource配置文件中,Product、Orders、Customers的导入路径正确,类名大小写一致(比如Product不要写成product)。
  • 检查实体类上的@Entity装饰器是否正确导入(import { Entity } from 'typeorm'),没有遗漏或写错。

3. 改用实体路径扫描

如果手动导入实体容易出错,可改用路径扫描让TypeORM自动识别实体:

// DataSource配置中替换entities字段
entities: [__dirname + '/../entities/**/*.entity.ts'], // 根据项目结构调整路径

4. 清理缓存重启服务

删除TypeScript编译输出目录(如dist)或node_modules/.cache,重新编译启动服务,避免缓存导致的元数据异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 02:50:27