Nestjs教程使用TypeORM进行数据库迁移与版本控制
在使用NestJS和TypeORM进行数据库迁移时遇到几个问题:
- 如何正确配置TypeORM的迁移文件生成路径?每次运行迁移命令生成的.ts文件都出现在根目录
- 团队协作时如何统一管理迁移版本?多人开发经常出现迁移文件顺序冲突
- 在NestJS项目中运行
typeorm migration:run
提示"无法找到数据源",但ormconfig.json配置是正确的 - 回滚迁移时出现"迁移表不存在"错误,但数据库明明有migrations表
- 生产环境部署时是否应该把迁移命令集成到CI/CD流程?最佳实践是什么?
- TypeORM迁移与NestJS的依赖注入系统如何配合使用?需要特别处理吗?
首先安装TypeORM和相关依赖:npm install @nestjs/typeorm typeorm pg
(pg是PostgreSQL驱动,根据你的数据库替换)。接着在app.module.ts
中配置TypeORM模块,例如:
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'your_username',
password: 'your_password',
database: 'your_db_name',
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: true, // 开发环境可开启,生产禁用
}),
],
})
export class AppModule {}
然后创建实体类,比如user.entity.ts
。接着安装迁移工具:npm install --save-dev @nestjs/cli
. 创建迁移文件:npx nest generate migration initial-create
.
编辑生成的迁移文件,定义表结构变化,如添加字段等。运行迁移:npx typeorm migration:run
。回滚迁移:npx typeorm migration:revert
.
TypeORM会自动维护migrations
表来记录已应用的迁移版本。每次修改实体或需求时,重复生成和运行迁移即可管理数据库版本。
在NestJS中使用TypeORM进行数据库迁移和版本控制,你需要以下步骤:
-
安装依赖:首先确保安装了TypeORM及相关工具:
npm install typeorm [@nestjs](/user/nestjs)/typeorm mysql2 npm install --save-dev ts-node [@types](/user/types)/node npm install --save-dev nodemon
-
配置TypeORM:在
src/main.ts
中初始化TypeORM模块,并在app.module.ts
中导入TypeOrmModule
。 -
创建实体:使用TypeORM装饰器定义你的数据模型,例如:
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; [@Entity](/user/Entity)() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; @Column() email: string; }
-
配置迁移:通过命令生成迁移文件:
npx typeorm migration:create -n InitialCreate
这会在
src/migration
目录下生成一个迁移文件。 -
编写迁移逻辑:编辑生成的迁移文件来定义SQL操作。
-
运行迁移:执行迁移以更新数据库结构:
npx typeorm migration:run
若要回滚,使用:
npx typeorm migration:revert
-
自动化脚本:添加到
package.json
的scripts部分方便执行:"scripts": { "migration:run": "typeorm migration:run", "migration:revert": "typeorm migration:revert" }
通过这些步骤,你可以实现NestJS项目中的数据库迁移与版本控制。每次修改实体后,重新生成并应用新的迁移文件即可保持数据库同步。
NestJS 使用 TypeORM 进行数据库迁移与版本控制教程
TypeORM 提供了强大的数据库迁移功能,可以帮助你管理数据库结构的变更。下面是在 NestJS 中使用 TypeORM 进行迁移的基本步骤:
1. 配置 TypeORM
首先确保你的 ormconfig.json
或 app.module.ts
中已正确配置 TypeORM:
// app.module.ts
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql', // 或其他数据库类型
host: 'localhost',
port: 3306,
username: 'root',
password: 'password',
database: 'test',
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: false, // 重要:生产环境必须设为 false
migrations: [__dirname + '/migrations/**/*{.ts,.js}'],
cli: {
migrationsDir: 'src/migrations',
},
}),
],
})
2. 创建迁移
在 package.json 中添加迁移脚本:
"scripts": {
"typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js",
"migration:generate": "npm run typeorm migration:generate -- -n",
"migration:run": "npm run typeorm migration:run",
"migration:revert": "npm run typeorm migration:revert"
}
生成新迁移文件:
npm run migration:generate -- InitialMigration
3. 编写迁移
生成的迁移文件示例:
import {MigrationInterface, QueryRunner} from "typeorm";
export class InitialMigration1589999999999 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`CREATE TABLE users (
id int NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
PRIMARY KEY (id)
)`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP TABLE users`);
}
}
4. 运行和回滚迁移
运行迁移:
npm run migration:run
回滚上一次迁移:
npm run migration:revert
5. 最佳实践
- 每个迁移应该只做一件事
- 编写完整的 up 和 down 方法
- 不要在迁移中处理业务数据
- 团队共享迁移文件
- 生产环境不要使用 synchronize: true
通过这种方式,你可以安全地管理数据库结构的变更,并随时回滚到之前的版本。