user.js 969 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. const mongoose = require('mongoose')
  2. const Schema = mongoose.Schema
  3. const bcrypt = require('bcrypt-nodejs')
  4. const UserSchema = new Schema({
  5. name: String,
  6. email: { type: String, unique: true, required: true },
  7. password: { type: String, required: true },
  8. address: { type:Schema.Types.ObjectId, ref: 'Address' }
  9. })
  10. UserSchema.pre('save', function(next) {
  11. let user = this
  12. if (this.isModified('password') || this.isNew) {
  13. // bcrypt.hash
  14. bcrypt.genSalt(10, function(err, salt) {
  15. if (err) {
  16. return next(err)
  17. }
  18. bcrypt.hash(user.password, salt, null, function (err, hash) {
  19. if (err) {
  20. return next (err)
  21. }
  22. user.password = hash
  23. next()
  24. })
  25. })
  26. } else {
  27. return next()
  28. }
  29. })
  30. UserSchema.methods.comparePassword = function (password, next) {
  31. let user = this
  32. return bcrypt.compareSync(password, user.password)
  33. }
  34. module.exports = mongoose.model('User', UserSchema)