Search code examples
typescriptauthenticationpostmannestjsbcrypt

How to use bcrypt module to save encrypted password in MongoDB using NestJS


How can I save an encrypted password to MongoDB?

P.S. I'm a beginner developer and still learning how to use NestJS


Solution

  • If you are using TypeOrm there is a decorator name's @BeforeInsert()

    @Entity("YourTable", { schema: "yourdb" })
    export class YourTable {
       ...
       @BeforeInsert()
       async hashPassword() {
          this.password = await bcrypt.hash(this.password, Number(process.env.HASH_SALT));
       }
       ...
    }