Search code examples
nestjstypeorm

NestJS + TypeORM Error during migration run: Unable to open file


I'm using NestJS to make an API and TypeORM to interface with my database.

I've configured my database as follows

app.modules.ts:

@Module({
  imports: [
    TypeOrmModule.forRoot({
    type: 'mysql',
    host: 'localhost',
    port: 3306,
    username: 'root',
    password: 'pass',
    database: 'test',
    autoLoadEntities: true,
    synchronize: true,
    migrations:['migrations/*{.ts,.js}']
   }),
CamerasModule
],
})
export class AppModule {}

All I want to do is run a migration by typing:

typeorm migration:run -d .\migrations\1654907799338-Camera.ts

I think part of the problem is that TypeORM isn't registering a DataSource, because if I just type

typeorm migration:run

it doesn't know where to look.

Anyways, the error I get is:

Error during migration run:
Error: Unable to open file: "C:\Users\sean\Documents\Git\db-api\migrations\1654907799338-Camera.ts". Cannot use import statement outside a module
    at Function.loadDataSource (C:\Users\sean\AppData\Roaming\nvm\v16.13.0\node_modules\typeorm\commands\CommandUtils.js:22:19)
    at async Object.handler (C:\Users\sean\AppData\Roaming\nvm\v16.13.0\node_modules\typeorm\commands\MigrationRunCommand.js:34:26)

Why is Nest failing to communicate with TypeORM?


Solution

  • typeorm migration:run -d .\migrations\1654907799338-Camera.ts this is incorrect path. I believe you are using v0.3.6. If so, the -d refers to the path of the data source and not the path of the migration file.

    In my case, i did it this way:

    "typeorm": "npx typeorm-ts-node-commonjs --dataSource src/data-source.ts",
    "typeorm:migrate": "yarn typeorm migration:run",
    "typeorm:generate": "yarn typeorm migration:generate src/database/migrations/Migration --timestamp",
    "typeorm:revert": "yarn typeorm migration:revert"
    

    where you must have data-source.ts in the root of src dir. You can find more information about DataSourceOptions in typeorm docs

    I spend a lot of thing figuring this out too. It seems that a new version of typeorm 0.3.6 is available and cli docs is outdated as of this writing.