Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var mongoose = require('mongoose');
- var bcrypt = require('bcryptjs');
- mongoose.connect('mongodb://localhost/saysomething');
- //mongoose user schema
- var UserSchema = mongoose.Schema({
- username:{
- type: String,
- index: true
- },
- password:{
- type: String,
- required: true,
- bcrypt: true
- },
- email:{
- type: String
- },
- name:{
- type: String
- },
- comments: []
- });
- //mongoose model
- var User = mongoose.model('User', UserSchema);
- module.exports = User;
- //METHODS
- //for Passport
- module.exports.comparePassword = function(candidatePassword, hash, callback){
- bcrypt.compare(candidatePassword, hash, function(err, isMatch) {
- if(err) return callback(err);
- callback(null, isMatch);
- });
- }
- //for Passport
- module.exports.getUserById = function(id, callback) {
- User.findById(id, callback);
- }
- //for Passport and adding comments to user
- module.exports.getUserByUsername = function(username, callback) {
- var query = {username: username};
- User.findOne(query, callback);
- }
- //make new user
- module.exports.createUser = function(newUser, callback){
- bcrypt.hash(newUser.password, 10, function(err, hash) {
- if(err) throw err;
- // set hashed password
- newUser.password = hash;
- //create User
- newUser.save(callback);
- });
- }
- //add comment to user
- module.exports.addComment = function(comment, username, callback) {
- var query = {username: username};
- User.findOneAndUpdate(
- query,
- {$push: {'comments': comment}},
- {safe: true, upsert: true},
- callback
- );
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement