【发布时间】:2018-06-26 04:04:23
【问题描述】:
我在我的项目中使用猫鼬,其中在使用 UserSchema.pre() 函数保存之前对密码进行哈希处理。它工作正常并加密了密码。但是,当我使用 UserSchema.methods.comparePassword 时,它会向我显示方法错误。方法被声明但从未使用过它的值。下面是我正在使用的代码
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt-nodejs');
const UserSchema = new Schema({
company_id: String,
branch_id: String,
name: String,
email : String,
password: String,
});
UserSchema.pre('save', function (next) {
var user = this;
if(!user.isModified('password')) return next();
if(user.password) {
bcrypt.genSalt(10, function(err, salt) {
if(err) return next(err);
bcrypt.hash(user.password, salt, null, function(err, hash) {
if(err) return next();
user.password = hash;
next(err)
})
})
}
});
UserSchema.methods.comparePassword = function(candidatePassword) {
return bcrypt.compareSync(candidatePassword, this.password);
};
module.exports = mongoose.model('User', UserSchema);
【问题讨论】:
标签: mongoose bcrypt mongoose-schema