Implement mongoose middleware part
npm i bcrypt
npm i -D @types/bcrypt
BCRYPT_SALT_ROUND=12 //.env file
bycrypt_salt_rounds: process.env.BCRYPT_SALT_ROUND, //.config file
//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();
});
//post save middleware
studentSchema.post('save', function (doc, next) {
doc.password = '';
// console.log('post hook: we save our data', this);
next();
});
Top comments (0)