【发布时间】:2017-12-07 12:44:30
【问题描述】:
我正在使用 Node.js、Mongoose、MongoDb、Express 开发应用程序。
当用户注册时,我试图在将密码保存在数据库中之前对密码进行哈希处理,但它似乎不起作用。密码保存没有散列,有什么建议吗?
'use strict'
let mongoose = require('mongoose')
let bcrypt = require('bcrypt-nodejs')
var Schema = mongoose.Schema
var userSchema = Schema({
name: { type: String, required: true, unique: true },
password: { type: String, required: true },
createdAt: {
type: Date,
require: true,
default: Date.now
}
})
// check if user already exists
userSchema.path('name').validate(function (name) {
User.findOne({name}, function (err, user) {
if (err) {
console.log('error')
} if (user) {
console.log('The user already exists')
console.log(user)
}
})
}, 'The user already exists')
// password validation
userSchema.path('password').validate(function (password) {
return password.length >= 6
}, 'The password must be of minimum length 6 characters.')
var User = mongoose.model('User', userSchema)
// hashing and adding salt pre save()
userSchema.pre('save', function (next) {
bcrypt.genSalt(10, function (err, salt) {
if (err) {
return next(err)
}
bcrypt.hash(this.password, salt, null, function (err, hash) {
// Store hash in your password DB.
if (err) {
return next(err)
}
// set the password to the hash
this.password = hash
})
next()
})
})
module.exports = User
【问题讨论】:
标签: javascript node.js mongodb mongoose