NestJS中TypeORM执行migration:run报错:需导出DataSource实例
This error happens because TypeORM v0.3+ requires a DataSource instance exported from your config file for migration commands, instead of just connection options. NestJS fully supports this approach—here's how to resolve the issue:
1. Update Your TypeORM Config File
Modify type-orm.config.ts to create and export a DataSource instance (not just options). Example:
import { DataSource } from 'typeorm'; import { ConfigService } from '@nestjs/config'; import { config } from 'dotenv'; // Load environment variables config(); const configService = new ConfigService(); // Create and export the DataSource instance export const AppDataSource = new DataSource({ type: 'postgres', // Replace with your database type (mysql, sqlite, etc.) host: configService.get<string>('DB_HOST'), port: configService.get<number>('DB_PORT'), username: configService.get<string>('DB_USERNAME'), password: configService.get<string>('DB_PASSWORD'), database: configService.get<string>('DB_NAME'), entities: [__dirname + '/../**/*.entity{.ts,.js}'], // Path to your entity files migrations: [__dirname + '/migrations/**/*{.ts,.js}'], // Path to migration files synchronize: false, // Disable this when using migrations (critical for production) });
2. Adjust Package.json Migration Scripts
Ensure your migration scripts point to the config file with the exported DataSource, using the -d flag to specify the path. Example:
{ "scripts": { "migration:generate": "typeorm-ts-node-commonjs migration:generate ./src/migrations/YourMigrationName -d ./src/config/type-orm.config.ts", "migration:run": "typeorm-ts-node-commonjs migration:run -d ./src/config/type-orm.config.ts", "migration:revert": "typeorm-ts-node-commonjs migration:revert -d ./src/config/type-orm.config.ts" } }
If your original script was named migration, update it to follow this pattern with the -d flag pointing to your config file.
3. Align NestJS App Module with the DataSource
Update app.module.ts to use the same DataSource configuration for your NestJS app:
import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { AppDataSource } from './config/type-orm.config'; @Module({ imports: [ TypeOrmModule.forRootAsync({ useFactory: () => AppDataSource.options, }), ], }) export class AppModule {}
This ensures your app and migrations share the same database configuration.
Key Notes
- TypeORM Version: This solution works for TypeORM v0.3.x and above. If you're on an older version, upgrade to use the DataSource approach (recommended) or use the legacy
createConnectionmethod. - Synchronize: Never set
synchronize: truein production—it can accidentally drop database tables. Always rely on migrations for schema changes.
内容的提问来源于stack exchange,提问作者kan

