簡體   English   中英

使用 nestjs 設置 typeorm 不工作遷移

[英]Setting up typeorm with nestjs not working migrations

這是配置:

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        type: 'postgres',
        host: configService.get('DB_HOST'),
        port: configService.get('DB_PORT'),
        username: configService.get('DB_USER'),
        password: configService.get('DB_PASSWORD'),
        database: configService.get('DB_NAME'),
        entities: [
          __dirname + '/../**/*.entity{.ts,.js}',
        ],
        // synchronize: true,
      })
    }),
  ],
})
export class DatabaseModule {}

與數據庫本身的連接正在工作,但是當我嘗試設置遷移時,它會引發錯誤。 我嘗試的是在上述配置中添加遷移選項並使用配置創建額外的 ormconfig.js。 這是我在 package.json 文件中的內容:

"typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js"

問題是當我嘗試創建遷移時,它沒有按照我的意願在遷移文件夾中創建,並且沒有使用上面的配置,如何解決?

TypeORM CLI 讀取項目根目錄下文件ormconfig.jsonormconfig.js中的配置。

您需要將這個配置提取到一個文件中,然后將該文件導入到您的 DatabaseModule 中,以使兩者都能正常工作。

如果您使用 typeorm 或 3.0 或更新版本,您應該直接在 cli 上執行:

typeorm migration:create src/migration_path

對於舊版本,您可以將以下命令添加到ormconfig文件中:

  "cli": {
    "migrationDir": "./src/migration_path"
  }

首先,您需要在模塊配置中設置遷移路徑

TypeOrmModule.forRootAsync({
    // other properties
    entities: [
      __dirname + '/../**/*.entity{.ts,.js}', // from the question
    ],
    migrations:[/*I assume you already know migration file paths*/]
})

然后,生成遷移文件

npx typeorm migration:create -n FileName -d src/migrations

此時,您需要調用runMigrations() 在您的main.ts中添加以下代碼

const conn = await getConnection('default'); // connection name is "default"
await conn.runMigrations();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM