how to proper handling typeorm entity columns in nestjs

Viewed 1461

i have been facing some difficulties in handling entity columns in coding, i mean adding or removing/deleting them from codes cause some issues in database here is how i tried to do

@Entity('user')
export class User {
  ....  other colums
  @Column()
  name: string;
}

The codes above will generate user table in database with appropriate column i.e name,

Now here is my issue later when i decide later to change column name to fullname

i get the following error QueryFailedError: column "fullname" of relation "user" contains null values

Even if i delete the user table and re-running the app,

Please assist!

2 Answers

i think i found the quick solution, i had to delete distfolder and everything works

To handle database modifications with TypeORM you can use two solutions, synchronize for automatic database changes and migrations for manually database changes.

Synchronize
Set the synchronize parameter to true to automatically update the database.

TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'root',
      database: 'test',
      entities: [],
      synchronize: true,
    }),

WARNING
Setting synchronize: true shouldn't be used in production - otherwise you can lose production data.

Learn more about synchronize

Migrations
This solution is the most used and must be used in production.

yarn typeorm migration:generate -n migrationName

This will generate you a migration file with database instructions based on your entities. You just need to run the migrations to apply the database changes.

yarn typeorm migration:up

Learn more about migrations

Related