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

TypeORM迁移报错:参数不足,需至少1个非选项参数

问题:TypeORM迁移生成失败,如何正确运行迁移创建数据库表?

项目结构

src
  ...
  app.ts
ormconfig.ts
tsconfig.ts

ormconfig.ts 文件内容

import 'reflect-metadata'
import { DataSource } from 'typeorm'
import Company from './src/entities/Company'
require('dotenv').config()

export const AppDataSource = new DataSource({
    type: 'mysql',
    host: process.env.DB_HOST,
    port: 3306,
    username: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    synchronize: true,
    logging: true,
    // entities: ['.entities/*.ts'],
    entities: [Company],
    migrations: ['.migrations/*.ts'],
})

package.json 脚本配置

"scripts": {
    "start": "node dist/app.js",
    "dev": "concurrently \"npx tsc --watch\" \"nodemon -q dist/app.js\"",
    "migration:generate": "./node_modules/.bin/ts-node ./node_modules/.bin/typeorm migration:generate -d .ormconfig.ts",
    "migration:create": "ts-node ./node_modules/typeorm/cli.js migration:generate -n initial -d .ormconfig.ts",
    "migration:down": "./node_modules/.bin/ts-node ./node_modules/.bin/typeorm migration:revert -d .ormconfig.ts"
  },

错误原因及修复方案

核心问题点

  1. 脚本命令路径重复调用,语法错误
  2. 迁移文件路径配置缺失根目录斜杠
  3. synchronize: true与迁移功能冲突(自动同步会覆盖迁移逻辑)

修复步骤

1. 修正 ormconfig.ts

import 'reflect-metadata'
import { DataSource } from 'typeorm'
import Company from './src/entities/Company'
import dotenv from 'dotenv'
import path from 'path'

dotenv.config()

export const AppDataSource = new DataSource({
    type: 'mysql',
    host: process.env.DB_HOST,
    port: 3306,
    username: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    synchronize: false, // 关闭自动同步,改用迁移管控表结构
    logging: true,
    entities: [path.join(__dirname, './src/entities/**/*.ts')], // 通配符匹配所有实体文件
    migrations: [path.join(__dirname, './migrations/**/*.ts')], // 修正迁移文件路径
})

2. 修正 package.json 脚本

"scripts": {
    "start": "node dist/app.js",
    "dev": "concurrently \"npx tsc --watch\" \"nodemon -q dist/app.js\"",
    "migration:generate": "ts-node ./node_modules/typeorm/cli.js migration:generate ./migrations/Initial -d ./ormconfig.ts",
    "migration:create": "ts-node ./node_modules/typeorm/cli.js migration:create ./migrations/Initial",
    "migration:run": "ts-node ./node_modules/typeorm/cli.js migration:run -d ./ormconfig.ts",
    "migration:down": "ts-node ./node_modules/typeorm/cli.js migration:revert -d ./ormconfig.ts"
  },

3. 执行迁移流程

  1. 创建迁移目录(如果不存在):
mkdir migrations
  1. 根据实体生成迁移文件:
npm run migration:generate
  1. 运行迁移创建数据库表:
npm run migration:run

额外注意事项

  • 确保.env文件中的数据库连接信息正确,且目标数据库已提前创建
  • 若使用TypeORM 0.2.x版本,需调整CLI命令格式为typeorm migration:generate -n Initial -d ormconfig.ts

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 23:27:19