NestJS/TypeORM. TypeORM doesn't update entity in DB, uses old cached entity instead
Solution 1:
You need to specify to your @PrimaryGeneratedColumn
to generate a UUID and not UIID or Integer as you tried.
# Not like this
@PrimaryGeneratedColumn("uiid")
id: string;
# Like this
@PrimaryGeneratedColumn("uuid")
id: string;
Here is how your entity need to be wrote specifying the UUID column type.
@Entity({ name: 'teacher' })
export class Teacher {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
username: string;
@Column()
email: string;
@Column()
password: string;
@BeforeInsert()
async hashPassword(): Promise<void> {
const salt = await bcrypt.genSalt(bcryptConstants.saltRounds);
const hash = await bcrypt.hash(this.password, salt);
this.password = hash;
}
}
About the delay when saving, Bcrypt is hashing your passwords and it takes a long time usually.
Solution 2:
As you already know NestJS is supposed to use TypeScript and then in order for the app to run on NodeJS, everything is translated to JavaScript and saved in the "dist" file, including entities written in TypeScript and TypeORM.
Because I changed the columns of my "teacher" entity many times and I later changed TypeORM's option to "synchronize: true", TypeORM used old files for entities from "dist" instead of using the updated ones that I have written in TypeScript.
So when you have TypeORM and "synchronize: true", TypeORM will create the tables in your database for you, but in my case it was building them using old/cached files from the "dist" directory.
How to fix it
Try to provide these options to TypeORM when importing it to your module
TypeOrmModule.forRoot({
autoLoadEntities: true,
synchronize: true,
...
}
OR
Delete your current dist folder and then run this command npm run build
so it can newly create the dist folder again and possibly remove old files.
Solution 3:
Simply clear your dist folder
rm -rf dist
Then run
yarn build // or npm run build