Search code examples
nestjstypeorm

Why my TypeORM can't connect database in product mode?


I am using Nest.js+TypeORM to develop and try to deploy in my computer.

I can connect to mysql in develop mode, but it failed in product mode.

Below is my TypeORM config.

@Module({
  imports: [
    AuthModule,
    ClassificationModule,
    ArticleModule,
    UserModule,
    CommentModule,
    FragmentModule,
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      // logging: ["query"],
      port: 3306,
      username: 'root',
      password: '123456',
      database: 'myblog',
      entities: ['src/**/**.entity{.ts,.js}'],
      synchronize: true
    })
  ]
})
export class AppModule { }

In develop mode, it can connect to mysql successfully.

enter image description here

But in product mode, it shows can't connect mysql.

enter image description here


Solution

  • ts-node manages your typescript compilation in memory and handles chaning references from src to dist internally. However, this is a problem when you get into running your pure node variant, as you'll be in a dist directory instead of src, so TypeORM won't be able to find your entities with the defined entities array. Instead you should use entities: [join(__dirname, '/**/*.entity.{js,ts}')], to allow for dynamically changing between ts and js so you don't have to worry about what you are running with.

    I would also suggest using tsc-watch for develpoment, as it will run node by default on successful compilation and you won't have to worry about memory consumption from ts-node.