Wolkendama-API / Model / userModel.js
userModel.js
Raw
const bcrypt = require("bcrypt");
const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, "User required a name!"],
  },
  username: {
    type: String,
    required: [true, "username is required"],
    unique: true,
    minlength: 6,
    select: false,
  },
  password: {
    type: String,
    required: [true, "password is required!"],
    minlength: 8,
    select: false,
  },
  passwordConfirm: {
    type: String,
    validate: {
      // This validate only works on CREATE and SAVE!
      validator: function (el) {
        return el === this.password;
      },
      message: "Password are not the same",
    },
    required: [true, "password confirm is required!"],
  },
});

userSchema.pre("save", async function (next) {
  // This refers to current query
  this.password = await bcrypt.hash(this.password, 12);
  this.passwordConfirm = undefined;
  next();
});

userSchema.methods.correctPassword = async (inputPassword, userPassword) =>
  await bcrypt.compare(inputPassword, userPassword);

const User = mongoose.model("User", userSchema);

module.exports = User;