MegaRoks
MegaRoks

Reputation: 948

Generating migrations doesn't see my connection

I made the connection to the database a separate module

@Module({
    imports: [
        TypeOrmModule.forRootAsync({
            imports: [ConfigModule],
            inject: [ConfigService],
            useFactory: configService => ({
                type: configService.get('DATABASE_TYPE'),
                host: configService.get('DATABASE_HOST'),
                port: configService.get('DATABASE_PORT'),
                username: configService.get('DATABASE_USERNAME'),
                password: configService.get('DATABASE_PASSWORD'),
                database: configService.get('DATABASE_NAME'),
                entities: ['./dist/**/*.entity.{js,ts}'],
                synchronize: false,
                migrationsRun: true,
                logging: true,
                migrations: ['./dist/modules/database/migration/*.{js,ts}'],
                cli: {
                    migrationsDir: 'src/modules/database/migration',
                },
            }),
        }),
    ],
})
export class DatabaseModule {}

This works fine in a docker container. But when I want to run the creation of the migration, I get the error

Error: No connection options were found in any orm configuration files.
    at ConnectionOptionsReader.<anonymous> (/Users/user1/Documents/app/src/connection/ConnectionOptionsReader.ts:43:19)

My commands for working with migrations

        "migration:generate": "ts-node node_modules/.bin/typeorm migration:generate -n",
        "migration:run": "ts-node node_modules/.bin/typeorm migration:run",
        "migration:revert": "ts-node node_modules/.bin/typeorm migration:revert"

In the command, I did not specify the connection konyig and as I understood orm cannot find my config for the connection, how can I tell it to me?

Upvotes: 1

Views: 1302

Answers (1)

user13331230
user13331230

Reputation:

Well the problem is that the CLI of TypeORM doesn't know that in your Nest application you use a TypeormModule to configure the connection. The CLI expects the config in the one of the following formats described in the documentation.

So the easiest way to fix your problem would be to create a file called ormconfig.js and set your connection config here. Like so:

module.exports = {
  "type": "mysql",
  "host": "localhost",
  "port": 3306,
  "username": "test",
  "password": "test",
  "database": "test"
}

Assuming that your configService reads the values from the environmental variables, you could also do:

module.exports = {
  "type": "mysql",
  "host": process.env.DB_HOST,
  "port": process.env.DB_PORT,
  "username": process.env.DB_USERNAME,
  "password": process.env.DB_PASSWORD,
  "database": process.env.DB_DATABASE
}

So that the config is the same as the one in the app.

Upvotes: 1

Related Questions