user.js 884 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import mongoose from 'mongoose'
  2. import bcrypt from 'bcrypt'
  3. const UserSchema = new mongoose.Schema({
  4. name: {
  5. type: String,
  6. unique: true,
  7. required: true
  8. },
  9. password: {
  10. type: String,
  11. required: true
  12. }
  13. })
  14. UserSchema.pre('save', function (next) {
  15. if (this.isModified('password') || this.isNew) {
  16. bcrypt.genSalt(10, (err, salt) => {
  17. if (err) {
  18. return next(err)
  19. }
  20. bcrypt.hash(this.password, salt, (err, hash) => {
  21. if (err) {
  22. return next(err)
  23. }
  24. this.password = hash
  25. next()
  26. })
  27. })
  28. } else {
  29. return next()
  30. }
  31. })
  32. UserSchema.methods.comparePassword = function (passwd, cb) {
  33. bcrypt.compare(passwd, this.password, (err, isMatch) => {
  34. if (err) {
  35. return cb(err)
  36. }
  37. cb(null, isMatch)
  38. })
  39. }
  40. const User = mongoose.model('User', UserSchema)
  41. export default User