Hassan2bit

password encrpytion before entering database: pre("save") function

a simple documentation on hashing password before saving into db

const userSchema = new mongoose.Schema({
  email: {
    type: String,
    required: true,
    unique: true,
    minlength: 4,
    lowercase: true,
  },
  username: {
    type: String,
    required: true,
    unique: true,
    minlength: 4,
    trim: true,
  },
  password: {
    type: String,
    required: true,
    minlength: 6,
  },

  createdAt: {
    type: Date,
    default: Date.now,
  },

  role: {
    default: "student",
    enum: ["student", "admin"],
    type: String,
  },
  premiumCourses: {
    type: [String],
    default: [],
  },
});

It is a no brainer to not save the plain password in the database, so we have to encrypt the password before it get recorded into the db storage.

so i'll be using bcrpyt hashing algorithm to hash the password...

to install "bcrypt" in a nodejs environment, we have to run:

npm install bcrypt

the goal is to encrpyt the password before entering the database, so we be using the pre-save function to do just that

userSchema.pre("save", async function (next) {
  if (!this.isModified("password")) {
    return next();
  }
  try {
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
  } catch (error) {
    next(error);
  }
});
module.exports = mongoose.model(User, userSchema);