简体   繁体   中英

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. Here is what I have in package.json file:

"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.

You need to extract this config in suck a file and then import this file in your DatabaseModule to have both things working.

If you're using typeorm or 3.0 or newer versions you should do it straight on the cli:

typeorm migration:create src/migration_path

For older versions, you can add the following command to the ormconfig file:

  "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() . add the below code in your main.ts

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM