Skip to content

Instantly share code, notes, and snippets.

@hariscs
Created March 2, 2024 13:06
Show Gist options
  • Select an option

  • Save hariscs/b7baf54ebd0897ccbce06bdaf930a75f to your computer and use it in GitHub Desktop.

Select an option

Save hariscs/b7baf54ebd0897ccbce06bdaf930a75f to your computer and use it in GitHub Desktop.
Hash and Match Password in a Model
import mongoose, { Document, Schema } from 'mongoose'
import bcrypt from 'bcrypt'
interface IUserSchema extends Document {
name?: string
email: string
password: string
match_password: (password: string) => Promise<boolean>
}
const user_schema = new Schema(
{
name: { type: String },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
},
{
timestamps: true,
}
)
user_schema.pre('save', async function (next) {
const user = this
if (!user.isModified('password')) {
next()
return
}
const salt = await bcrypt.genSalt(10)
this.password = await bcrypt.hash(this.password, salt)
next()
})
user_schema.methods.match_password = async function (entered_password: string) {
return await bcrypt.compare(entered_password, this.password)
}
export const USER_SCHEMA = mongoose.model<IUserSchema>('User', user_schema)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment