1234567891011121314151617181920212223242526272829303132333435363738394041 |
- const mongoose = require('mongoose')
- const Schema = mongoose.Schema
- const bcrypt = require('bcrypt-nodejs')
- const UserSchema = new Schema({
- name: String,
- email: { type: String, unique: true, required: true },
- password: { type: String, required: true },
- address: { type:Schema.Types.ObjectId, ref: 'Address' }
- })
- UserSchema.pre('save', function(next) {
- let user = this
- if (this.isModified('password') || this.isNew) {
- // bcrypt.hash
- 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()
- })
- })
- } else {
- return next()
- }
- })
- UserSchema.methods.comparePassword = function (password, next) {
- let user = this
- return bcrypt.compareSync(password, user.password)
- }
- module.exports = mongoose.model('User', UserSchema)
|