简体   繁体   English

使用 nestjs 设置 typeorm 不工作迁移

[英]Setting up typeorm with nestjs not working migrations

Here is the config:这是配置:

@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 {}

The connections with the database itself is working, but when I'm trying to set up the migrations it throws the errors.与数据库本身的连接正在工作,但是当我尝试设置迁移时,它会引发错误。 What I've tried is to add the migration options in the above config and to create additional ormconfig.js with the configurations.我尝试的是在上述配置中添加迁移选项并使用配置创建额外的 ormconfig.js。 Here is what I have in package.json file:这是我在 package.json 文件中的内容:

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

The problem is when I try to create migration it is not being created in migrations folder as I want and is not using the config above, how to solve it?问题是当我尝试创建迁移时,它没有按照我的意愿在迁移文件夹中创建,并且没有使用上面的配置,如何解决?

TypeORM CLI reads the configuration in a file ormconfig.json or ormconfig.js at the root of the project. TypeORM CLI 读取项目根目录下文件ormconfig.jsonormconfig.js中的配置。

You need to extract this config in suck a file and then import this file in your DatabaseModule to have both things working.您需要将这个配置提取到一个文件中,然后将该文件导入到您的 DatabaseModule 中,以使两者都能正常工作。

If you're using typeorm or 3.0 or newer versions you should do it straight on the cli:如果您使用 typeorm 或 3.0 或更新版本,您应该直接在 cli 上执行:

typeorm migration:create src/migration_path

For older versions, you can add the following command to the ormconfig file:对于旧版本,您可以将以下命令添加到ormconfig文件中:

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

First, you need to set the migrations path in the module config首先,您需要在模块配置中设置迁移路径

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

then, To generate a migration file然后,生成迁移文件

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

At this point, you need to call runMigrations() .此时,您需要调用runMigrations() add the below code in your main.ts在您的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