Advertisement
Guest User

Untitled

a guest
Feb 9th, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. var mongoose = require('mongoose');
  2. var bcrypt = require('bcryptjs');
  3.  
  4. mongoose.connect('mongodb://localhost/saysomething');
  5.  
  6. //mongoose user schema
  7. var UserSchema = mongoose.Schema({
  8. username:{
  9. type: String,
  10. index: true
  11. },
  12. password:{
  13. type: String,
  14. required: true,
  15. bcrypt: true
  16. },
  17. email:{
  18. type: String
  19. },
  20. name:{
  21. type: String
  22. },
  23. comments: []
  24. });
  25.  
  26.  
  27. //mongoose model
  28. var User = mongoose.model('User', UserSchema);
  29. module.exports = User;
  30.  
  31.  
  32. //METHODS
  33. //for Passport
  34. module.exports.comparePassword = function(candidatePassword, hash, callback){
  35. bcrypt.compare(candidatePassword, hash, function(err, isMatch) {
  36. if(err) return callback(err);
  37. callback(null, isMatch);
  38. });
  39. }
  40.  
  41. //for Passport
  42. module.exports.getUserById = function(id, callback) {
  43. User.findById(id, callback);
  44. }
  45.  
  46. //for Passport and adding comments to user
  47. module.exports.getUserByUsername = function(username, callback) {
  48. var query = {username: username};
  49. User.findOne(query, callback);
  50. }
  51.  
  52. //make new user
  53. module.exports.createUser = function(newUser, callback){
  54. bcrypt.hash(newUser.password, 10, function(err, hash) {
  55. if(err) throw err;
  56. // set hashed password
  57. newUser.password = hash;
  58. //create User
  59. newUser.save(callback);
  60. });
  61. }
  62.  
  63. //add comment to user
  64. module.exports.addComment = function(comment, username, callback) {
  65. var query = {username: username};
  66. User.findOneAndUpdate(
  67. query,
  68. {$push: {'comments': comment}},
  69. {safe: true, upsert: true},
  70. callback
  71. );
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement