Guest User

Untitled

a guest
Apr 27th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. const mongoose = require('mongoose');
  2. const bcrypt = require('bcrypt');
  3.  
  4. const userSchema = new mongoose.Schema({
  5. username: {
  6. type: String,
  7. required: true,
  8. unique: true,
  9. lowercase: true,
  10. // normalize all users to lowercase
  11. // helps later when making queries
  12. },
  13. password: {
  14. type: String,
  15. required: true,
  16. minlength: 4, // make this at least 10 or 12
  17. // in a production application
  18. },
  19. race: {
  20. type: String,
  21. required: true,
  22. },
  23. });
  24.  
  25. userSchema.pre('save', function(next) {
  26. // const user = this; // scope is the document
  27. // you need to do this if the function passed to
  28. // then is a regular function, not an arrow
  29. // function to make sure the binding of this
  30. // is correct. See code below.
  31. // bcrypt.hash(this.password, 10).then(function(hash) {
  32.  
  33. bcrypt.hash(this.password, 10).then(hash => {
  34. // different scope if using function(hash)
  35. // same document scope if using arrow function
  36. this.password = hash;
  37.  
  38. next();
  39. });
  40. });
  41.  
  42. userSchema.methods.verifyPassword = function(guess, callback) {
  43. bcrypt.compare(guess, this.password, function(err, isValid) {
  44. if (err) {
  45. return callback(err);
  46. }
  47.  
  48. // here there was no error
  49. callback(null, isValid);
  50. });
  51. };
  52.  
  53. module.exports = mongoose.model('User', userSchema, 'users');
Add Comment
Please, Sign In to add comment