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

TypeORM生成迁移报错:未检测到数据库架构变更

问题描述

执行TypeORM迁移生成命令时出现报错:

No changes in database schema were found - cannot generate a migration. To create a new empty migration use "typeorm migration:create" command

之前正常运行的旧项目现在也出现相同问题,已确认路径配置无误,但报错仍存在。

相关配置文件如下:

package.json

{
  "dependencies": {
    "@types/body-parser": "^1.19.2",
    "@types/cors": "^2.8.12",
    "@types/dotenv": "^8.2.0",
    "@types/express": "^4.17.14",
    "@types/nodemon": "^1.19.2",
    "body-parser": "^1.20.0",
    "cors": "^2.8.5",
    "dotenv": "^16.0.2",
    "express": "^4.18.1",
    "nodemon": "^2.0.20",
    "pg": "^8.8.0",
    "reflect-metadata": "^0.1.13",
    "rimraf": "^3.0.2",
    "ts-node": "^10.9.1",
    "typeorm": "^0.3.9",
    "typescript": "^4.8.3"
  },
  "name": "ecomerce_api_payment",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "build": "rimraf dist & tsc",
    "dev": "nodemon --exec ts-node ./src/server.ts",
    "migration:generate": "typeorm-ts-node-commonjs -d ./src/database/config.ts migration:generate ./src/database/migrations/default",
    "migration:run": "typeorm-ts-node-commonjs -d ./src/database/config.ts migration:run"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": ""
}

database/config.ts

import { DataSource } from "typeorm"
import dotenv from 'dotenv';

dotenv.config();

const port = process.env.DATABASE_PORT as number | undefined

export const AppDataSource = new DataSource({
    type: "postgres",
    host: process.env.DATABASE_HOST,
    port: port,
    username: process.env.DATABASE_USERNAME,
    password: process.env.DATABASE_PASSWORD,
    database: process.env.DATABASE_NAME,
    synchronize: true,
    entities: [`${__dirname}/../entities/*.{ts,js}`],
    migrations: [`${__dirname}/migrations/*.{ts,js}`],
})
解决方案

1. 关闭synchronize选项

配置中synchronize: true会自动将实体同步到数据库,导致TypeORM无法检测到需要迁移的变更。生成迁移前必须将其设为false:

export const AppDataSource = new DataSource({
    // ...其他配置
    synchronize: false,
    // ...
})

2. 确认实体文件加载正常

  • 检查entities路径是否准确:${__dirname}/../entities/*.{ts,js},确保实体文件确实在src/entities目录下,且文件名后缀正确。
  • 实体类必须添加@Entity()装饰器,TypeORM才会将其识别为数据库实体。

3. 验证数据库连接有效性

确保dotenv正确加载了环境变量,数据库连接信息无误。可在配置文件中添加连接测试代码:

AppDataSource.initialize()
  .then(() => {
    console.log("Data Source has been initialized!")
  })
  .catch((err) => {
    console.error("Error during Data Source initialization", err)
  })

运行项目确认能正常连接数据库。

4. 清理迁移历史表

TypeORM会在数据库中创建migrations表记录已执行的迁移,若表中数据异常可能导致检测失效:

  • 手动删除migrations表中的所有记录(不要删除表本身)
  • 或删除所有已生成的迁移文件,重新生成初始迁移

5. 检查TypeORM版本兼容性

你使用的是TypeORM 0.3.x版本,该版本与旧版本的命令、配置存在差异:

  • 确认typeorm-ts-node-commonjs命令正确,对应CommonJS模块模式(你的项目使用ts-node,该模式是正确的)
  • 检查tsconfig.json中的module设置为CommonJS,避免模块加载问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 12:55:25