Guest User

Untitled

a guest
Jan 16th, 2019
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. const mongoose = require('mongoose');
  2. const Schema = mongoose.Schema;
  3. const bcrypt = require('bcrypt-nodejs');
  4.  
  5. const UserSchema = new Schema({
  6. email : {
  7. type : String,
  8. unique : true
  9. },
  10. username: String,
  11. password: String,
  12. });
  13.  
  14. UserSchema.pre('save', function (next) {
  15. var user = this;
  16. if (this.isModified('password') || this.isNew) {
  17. bcrypt.genSalt(10, function (err, salt) {
  18. if (err) {
  19. return next(err);
  20. }
  21. bcrypt.hash(user.password, salt, null, function (err, hash) {
  22. if (err) {
  23. return next(err);
  24. }
  25. user.password = hash;
  26. next();
  27. });
  28. });
  29. } else {
  30. return next();
  31. }
  32. });
  33.  
  34. UserSchema.methods.comparePassword = function (pwd, cb) {
  35. bcrypt.compare(pwd, this.password, function (err, isMatch) {
  36. if (err) {
  37. return cb(err);
  38. }
  39. cb(null, isMatch);
  40. });
  41. };
  42.  
  43. module.exports = mongoose.model('user', UserSchema);
Add Comment
Please, Sign In to add comment