{"size": 1236, "ext": "js", "max_stars_repo_path": "models/user.js", "max_stars_repo_name": "Rock-son/authBoilerplate", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/user.js", "max_issues_repo_name": "Rock-son/authBoilerplate", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/user.js", "max_forks_repo_name": "Rock-son/authBoilerplate", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 27.4666666667, "max_line_length": 97, "alphanum_fraction": 0.6359223301}
const mongoose = require("mongoose"),
      bcrypt = require("bcrypt-nodejs"),
      Schema = mongoose.Schema;

// Define Model
const userSchema = new Schema({
    // unique String.toLowerCase() - so no doubles are possible
    email: { type: Schema.Types.String, unique: true, lowercase: true },
    password: String
});



// On Save Hook, encrypt password with bcrypt
userSchema.pre("save", function(next) {
    
    const user = this; // user is an instance of userSchema - a context (this)
    bcrypt.genSalt(10, function(err, salt) {
        if (err) { return next(err); }

        bcrypt.hash(user.password, salt, null, function(err, hash) {
            if (err) { return next(err); }

            user.password = hash;
            next();  // e.g. go ahead, save the model
        });
    });
});




userSchema.methods.comparePassword = function(candidatePassword, callback) {
    bcrypt.compare(candidatePassword, this.password, function(err, isMatch) { // "this" as a User
        if (err) { return callback(err); }

        callback(null, isMatch);
    });
};

// Create Model Class from Schema and collection name
const ModelClass = mongoose.model("user", userSchema, "users");

// Export Model
module.exports = ModelClass;