我在我的项目中使用了mongoose,在使用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);发布于 2018-06-26 04:04:24
你可以搭乘.methods UserSchema.comparePassword应该没问题
https://stackoverflow.com/questions/51021356
复制相似问题