未定义的函数与bcrypt-nodejs

我正在使用bcrypt-nodejs在预保存函数内对密码进行哈希处理。 我不明白为什么我继续在bcrypt.hash的callback函数里面收到'[TypeError:undefined不是一个函数]'的错误。

var mongoose = require('mongoose'), validate = require('mongoose-validate'), bcrypt = require('bcrypt-nodejs'), SALT_WORK_FACTOR = 10, REQUIRED_PASSWORD_LENGTH = 8; function validateStringLength (value) { return value && value.length >= REQUIRED_PASSWORD_LENGTH; } var schema = mongoose.Schema({ email: {type: String, required: true, unique: true, validate: [validate.email, 'is not a valid email address'] }, passHash: {type: String, required: true, validate: [validateStringLength, 'The password must be of min ' + REQUIRED_PASSWORD_LENGTH + ' characters length.']} }); schema.pre('save', function (next) { var self = this; if (!self.isModified('passHash')) return next(); bcrypt.hash(self.passHash, SALT_WORK_FACTOR, null, function encryptedPassword (err, hash) { if(err) console.log(err); self.passHash = hash; next(); }); }); schema.set('autoIndex', App.env !== 'production'); var Model = mongoose.model('User', schema); module.exports = Model; 

我检查了传递的参数,他们是正确的。 此外,返回的散列值为空。

有没有人有类似的经历? 我正在使用bcrypt-nodejs,因为在使用npm进行安装时,bcrypt会给我提供错误。

可再生的这个:

 var bcrypt = require('bcrypt-nodejs') bcrypt.hash('foo', 10, null, function(err) { if (err) throw err; }); 

问题是盐需要是一个string(在内部, bcrypt-nodejs使用salt.charAt()charAt()未定义数字)。

你可能想要这个:

  bcrypt.hash(self.passHash, bcrypt.genSaltSync(SALT_WORK_FACTOR), ...); 

(或asynchronous版本, bcrypt.genSalt()