DEV Community

Kazi Abdur Rakib
Kazi Abdur Rakib

Posted on

password hash in express, mongoose using bcrypt

Implement mongoose middleware part

npm i bcrypt
npm i -D @types/bcrypt
Enter fullscreen mode Exit fullscreen mode
BCRYPT_SALT_ROUND=12 //.env file
 bycrypt_salt_rounds: process.env.BCRYPT_SALT_ROUND, //.config file

Enter fullscreen mode Exit fullscreen mode
//Encrypt & pre save middleware/hook: will work on create on save function
studentSchema.pre('save', async function (next) {
  // console.log('pre hook: we save our data', this);

  //hashing password and save into DB
  // eslint-disable-next-line @typescript-eslint/no-this-alias
  const user = this; // documents
  user.password = await bcrypt.hash(
    user.password,
    Number(config.bycrypt_salt_rounds),
  );
  next();
});

Enter fullscreen mode Exit fullscreen mode
//post save middleware 
studentSchema.post('save', function (doc, next) {
  doc.password = '';
  // console.log('post hook: we save our data', this);
  next();
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)