Skip to content

Instantly share code, notes, and snippets.

@chewtoys
Created July 29, 2019 19:19
Show Gist options
  • Save chewtoys/c22970fd10adffed9c0f6a805a8301fe to your computer and use it in GitHub Desktop.
Save chewtoys/c22970fd10adffed9c0f6a805a8301fe to your computer and use it in GitHub Desktop.
const userSchema = new mongoose.Schema({
password: {
type: String,
required: true,
minlength: 6,
maxlength: 128,
}, {
timestamps: true,
})
userSchema.pre('save', async function save(next) {
try {
if (!this.isModified('password')) return next()
const rounds = env === 'test' ? 1 : 10
const hash = await bcrypt.hash(this.password, rounds)
this.password = hash
return next()
} catch (error) {
return next(error)
}
})
userSchema.method({
async passwordMatches(password) {
return bcrypt.compare(password, this.password)
},
})
module.exports = mongoose.model('User', userSchema)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment