Search code examples
nestjsmikro-orm

Use MikroORM migrations with NestJs


I'm running into problem using command mikro-orm migration:create. Console shows me Error: MikroORM config file not found in ['./dist/mikro-orm.config.js', './mikro-orm.config.js']. My app.module looks like this:

  @Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    MikroOrmCoreModule.forRootAsync({
      useFactory: (configService: ConfigService) => ({
        entitiesTs: [`./shared/db/entities`],
        entities: [`./dist/shared/db/entities`],
        user: configService.get<string>('DB_NAME'),
        password: configService.get<string>('DB_PASSWORD'),
        dbName: configService.get<string>('DB_NAME'),
        port: configService.get<number>('DB_PORT'),
        type: 'postgresql',
        migrations: {
          tableName: 'migrations',
          path: `./dist/shared/db/migrations`,
          pathTs: `./shared/db/entities`,
          glob: '!(*.d).{js,ts}',
          transactional: true,
          allOrNothing: true,
          emit: 'ts',
        },
      }),
      inject: [ConfigService],
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Aslo I've tried to create mikro-orm.config file with same setup, but then console shows me something like Error: No entities discovered. I've tried different ways of define paths in all related fields (entitiesTs, entities, path, pathTs) such as using */__dirname/process.pwd() in path, but it didn't help.


Solution

  • Keep the configuration only in the mikro-orm.config.ts file, configure the ORM to find it as described in docs (namely the configPaths and useTsNode in your package.json), then you can use this config in your app.module.ts, just import it and spread to the place where you have the options now. Then you can use the npx mikro-orm debug command to check how the paths look for the ORM.

    import config from './mikro-orm.config';
    
    @Module({
      imports: [
        ConfigModule.forRoot({ isGlobal: true }),
        MikroOrmCoreModule.forRootAsync({
          useFactory: (configService: ConfigService) => ({
            ...config,
          }),
          inject: [ConfigService],
        }),
      ],
      controllers: [AppController],
      providers: [AppService],
    })
    export class AppModule {}
    

    This way you get a single source of truth for both the CLI and your app, so you can use the CLI to debug the config easily.