【发布时间】:2017-08-02 01:27:10
【问题描述】:
我正在尝试使用以下 .pre() 挂钩对密码进行哈希处理:
import * as bcrypt from 'bcrypt'; // "bcrypt": "^1.0.2"
(<any>mongoose).Promise = require('bluebird');
const user_schema = new Schema({
email: { type: String, required: true },
password: { type: String, required: true },
})
const SALT_WORK_FACTOR = 10;
user_schema.pre('save', function (next) {
const user = this;
if (!user.isModified('password')) return next();
bcrypt.hash(user.password, SALT_WORK_FACTOR, function (error, hash) {
if (error) return next(error);
user.password = hash;
console.log(hash); // properly consoles the hash
next();
});
});
正如我在上面提到的,哈希值正确地控制台,所以它被正确地制作。但是,当我这样保存时:
const x = new MongoUser({
'_id': mongoose.Types.ObjectId(),
'email': 'test@test.com',
'password': 'testp@$$word',
})
console.log(x); // this consoles the object properly
x.save(function(err: any){
console.log('callback fired'); // this does not
if (err) console.log(err)
});
我发现从未调用过save() 回调。
我可以通过删除.pre90 挂钩或将bcrypt.hash() 替换为next() 调用来使用未哈希密码执行save(),用户使用未哈希密码保存,因此我对架构实现和数据库连接。
为什么save() 没有被触发?
这也不是竞争问题,因为我 tcs 文件然后运行单独的执行脚本
【问题讨论】:
-
我不确定您是否已经解决了这个问题。它可能与您使用的 mongoose/nodejs/bcrypt 版本有关。它可以与
bcrypt 1.0.2, mongoose 4.8.6和node js v7.2.0一起正常工作。 -
我已更新到最新版本,但仍然无法正常工作。
标签: typescript mongoose bcrypt