如何在NestJS 10中指定TypeORM的迁移文件夹?
问题
使用NestJS 10 + TypeORM 0.3.17,需从src/entities/user.entity.ts的User实体生成迁移,实体代码如下:
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm'; @Entity() export class User { @PrimaryGeneratedColumn() id: string; @Column() firstName: string; @Column() lastName: string; }
package.json中配置的迁移脚本:
"migration:run": "npm run typeorm migration:run -- -d ./src/config/typeorm.ts", "migration:generate": "npm run typeorm -- -d ./src/config/typeorm.ts migration:generate ./src/migrations/$npm_config_name", "migration:create": "npm run typeorm -- migration:create ./src/migrations/$npm_config_name", "migration:revert": "npm run typeorm -- -d ./src/config/typeorm.ts migration:revert"
执行npx typeorm migration:create -o UserData -d src/migrations时触发错误:
$ npx typeorm migration:create -o UserData -d src/migrations typeorm migration:create <path> Creates a new migration file. Options: -h, --help Show help [boolean] -o, --outputJs Generate a migration file on Javascript instead of Typescript [boolean] [default: false] -t, --timestamp Custom timestamp for the migration name [number] [default: false] -v, --version Show version number [boolean] Unknown argument: d
求正确生成关联User实体的迁移并指定到目标文件夹的方法。
解决方案
1. 明确两个迁移命令的区别
migration:create:生成空的迁移文件,需手动编写SQL,无需数据源连接,也不会关联实体。该命令没有-d(数据源配置)参数,这是报错的核心原因。migration:generate:根据实体与数据库的差异自动生成迁移逻辑,必须指定数据源配置文件(-d)。
2. 自动生成关联User实体的迁移
直接使用已配置的migration:generate脚本:
npm run migration:generate --name=UserData
该命令会:
- 读取
src/config/typeorm.ts中的数据源配置 - 对比User实体与数据库的当前状态
- 在
src/migrations目录下生成带时间戳的[timestamp]-UserData.ts迁移文件
3. 手动创建空迁移文件(若需自定义逻辑)
使用配置好的migration:create脚本:
npm run migration:create --name=UserData
会在src/migrations下生成空的迁移文件,文件名包含时间戳和指定的UserData后缀。
4. 关键注意事项
- 确保
src/config/typeorm.ts中正确配置实体路径,例如:
否则TypeORM无法识别User实体。entities: [__dirname + '/../entities/*.entity.ts'] - 执行迁移生成前,需保证数据库连接正常,
typeorm.ts中的数据库配置信息准确。
内容的提问来源于stack exchange,提问作者Dave
相关产品推荐
相关产品推荐

