12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- import mongoose from 'mongoose'
- import bcrypt from 'bcrypt'
- const UserSchema = new mongoose.Schema({
- name: {
- type: String,
- unique: true,
- required: true
- },
- password: {
- type: String,
- required: true
- }
- })
- UserSchema.pre('save', function (next) {
- if (this.isModified('password') || this.isNew) {
- bcrypt.genSalt(10, (err, salt) => {
- if (err) {
- return next(err)
- }
- bcrypt.hash(this.password, salt, (err, hash) => {
- if (err) {
- return next(err)
- }
- this.password = hash
- next()
- })
- })
- } else {
- return next()
- }
- })
- UserSchema.methods.comparePassword = function (passwd, cb) {
- bcrypt.compare(passwd, this.password, (err, isMatch) => {
- if (err) {
- return cb(err)
- }
- cb(null, isMatch)
- })
- }
- const User = mongoose.model('User', UserSchema)
- export default User
|