Created
July 29, 2019 19:19
-
-
Save chewtoys/c22970fd10adffed9c0f6a805a8301fe to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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