Advertisement
Guest User

Untitled

a guest
Dec 12th, 2016
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. const mongoose = require('mongoose')
  2. const bcrypt = require('bcrypt')
  3. const Schema = mongoose.Schema
  4. // let ObjectId = Schema.ObjectId
  5.  
  6. let userSchema = new Schema({
  7. username: {type: String, unique: true},
  8. password: {type: String, required: true},
  9. email: {type: String, required: true},
  10. admin: Boolean,
  11. created_at: Date,
  12. updated_at: Date
  13. })
  14.  
  15. userSchema.pre('save', function (next) {
  16. let user = this
  17. let currentDate = new Date()
  18. this.updated_at = currentDate
  19. if (!this.created_at) {
  20. this.created_at = currentDate
  21. }
  22. if (user.isModified('password')) {
  23. bcrypt.hashSync(user.password, 8)
  24. }
  25. next()
  26. })
  27.  
  28. userSchema.statics.comparePassword = function (password, hash) {
  29. return new Promise((resolve) => {
  30. if (bcrypt.compareSync(password, hash)) {
  31. resolve(true)
  32. } else {
  33. resolve(false)
  34. }
  35. })
  36. }
  37. userSchema.statics.findByEmail = function (email, cb) {
  38. return this.find({email: email}, cb)
  39. }
  40.  
  41. module.exports = mongoose.model('User', userSchema)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement