Mini-CRUD-app/models/User.js
2025-06-03 11:51:54 +05:30

42 lines
854 B
JavaScript

const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const userSchema = new mongoose.Schema({
first_name: {
type: String,
required: false,
},
last_name: {
type: String,
},
email: {
type: String,
required: true,
unique: true,
},
age: {
type: Number,
},
username: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
});
userSchema.pre("save", async function (next) {
if (!this.isModified("password")) return next();
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
next();
});
userSchema.methods.matchPassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
};
module.exports = mongoose.model("User", userSchema);