Skip to main content
100%

Gist cb0863f6e1b515510fa87520bd854996

✓ Published0🌍 Public
Aabernier
Last edited Jun 13, 2021
Created on Jan 20, 2020

This example demonstrates how to automatically hash a user's password before saving it to a MongoDB database using Mongoose middleware. The code defines a `User` schema with email and password fields, then attaches a `pre('save')` hook that checks if the password was modified and applies bcrypt’s `hashSync` function with a salt factor of 10. It also includes a `comparePassword` method that uses `bcrypt.compare` to verify passwords. The example shows a test case where a new user is created and saved, logging the resulting bcrypt-hashed password.

AI-generated description

Using Mongoose pre middleware to systematically hash a User's password

const myuser = new User({
  email: 'jdoe@hotmail.fr',
  password: 'blacky123'
})

myuser.save()
  .then(jdoe => {
    console.log(jdoe.password) // $2b$10$nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
  })
  .catch(console.error)

Similar vizzes