TypeORM does not create tables, columns etc

bersling picture bersling · Oct 20, 2017 · Viewed 19.4k times · Source

I have set up a system with typeorm (https://github.com/typeorm/typeorm) and NestJs (https://github.com/nestjs/nest), but TypeORM isn't creating the tables or columns. My setup is like this:

import {UserPassword} from '../user/user-password.entity';
import {User} from '../user/user.entity';

createConnection({
    type: 'mysql',
    host: 'typeorm2.cn32tstd6wqk.eu-central-1.rds.amazonaws.com',
    port: 1234,
    username: 'username',
    password: 'password',
    database: 'dbname',
    entities: [
      // __dirname + '/../**/*.entity{.ts,.js}'
      UserPassword,
      User
    ]
  })

And the entities are:

import {Entity, Column, PrimaryGeneratedColumn, OneToOne, JoinColumn} from 'typeorm';

@Entity()
export class UserPassword {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  hash: string;

  @Column()
  algorithm: string;

}

and

import {Entity, Column, PrimaryGeneratedColumn, OneToOne, JoinColumn} from 'typeorm';
import {UserPassword} from './user-password.entity';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ length: 35 })
  firstName: string;

  @Column({ length: 35 })
  lastName: string;

  @Column({ length: 50})
  mail: string;

  @OneToOne(type => UserPassword)
  @JoinColumn()
  password: UserPassword;

}

Then I try to create a user like this:

// ... some code
await this.userPasswordRepository.save(userPassword);
return await this.userRepository.save(user);

But I get the following error:

QueryFailedError: ER_NO_SUCH_TABLE: Table 'typeorm2.user_password' doesn't exist

When I insert the table manually then I get the error:

QueryFailedError: ER_BAD_FIELD_ERROR: Unknown column 'hash' in 'field list'

So it seems like TypeORM doesn't generate the tables / columns. Does anyone know why this could be?

Answer

Bogdan Surai picture Bogdan Surai · Jan 3, 2019

Connection has ‘synchronize()’ method. You can use it to create tables and columns automatically:

const connection = await createConnection(...);
await connection.synchronize();