TypeORM v0.3.6 + NestJS异步加载迁移配置报错求助
解决NestJS + TypeORM 0.3.6迁移时找不到实体的问题
直接排查以下核心问题:
1. 迁移配置文件的实体路径必须准确
TypeORM CLI不会自动读取NestJS模块里的实体配置,所以typeorm-migration.config.ts得手动指定实体路径,建议用path模块拼接绝对路径避免跨平台问题,示例配置如下:
import { DataSource } from 'typeorm'; import * as dotenv from 'dotenv'; import * as path from 'path'; // 手动加载.env文件——CLI不会自动调用Nest的ConfigService dotenv.config(); export default new DataSource({ type: 'postgres', // 替换为你的数据库类型 host: process.env.DB_HOST, port: parseInt(process.env.DB_PORT), username: process.env.DB_USERNAME, password: process.env.DB_PASSWORD, database: process.env.DB_NAME, // 关键:用glob匹配所有实体文件,路径要和你的项目结构对应 entities: [path.join(__dirname, 'src/**/*.entity.ts')], migrations: [path.join(__dirname, 'src/migrations/*.ts')], synchronize: false, });
如果你的项目是ES模块(package.json里type: module),要把配置文件后缀改成.mjs,同时CLI命令换成typeorm-ts-node-esm。
2. 检查package.json的迁移脚本格式
TypeORM 0.3.x的CLI命令必须指定数据源配置文件,脚本要这么写:
{ "scripts": { "typeorm:generate-migration": "typeorm-ts-node-commonjs migration:generate ./src/migrations/$npm_config_name -d ./typeorm-migration.config.ts" } }
其中-d参数必须指向你的迁移配置文件,$npm_config_name用来接收你传的--name参数。
3. 确认实体文件的装饰器和导出正确
每个实体类必须用@Entity()装饰,且导出方式要匹配配置的路径规则:
// src/yandex-ndd-api-client/entity/business-log.entity.ts import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm'; @Entity() export class BusinessLog { @PrimaryGeneratedColumn() id: number; @Column() content: string; }
4. 清除TypeScript缓存后重试
缓存可能导致路径识别异常,先执行:
npx tsc --clean
再重新运行迁移生成命令。
内容的提问来源于stack exchange,提问作者Illusion
相关产品推荐
相关产品推荐

