我尝试使用以下.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()
回调。
我可以通过移除save()
挂钩或使用.pre90
替换bcrypt.hash()
来保存用户使用未加密码的密码保存,使用未加密码的密码执行next()
,所以我对模式实现和数据库连接充满信心。
为什么save()
没有被触发?
这不是种族问题,因为我tcs
文件,然后运行单独的执行脚本
答案 0 :(得分:0)
您可能错过了一些步骤。下面的代码适合我。我在bcrypt 1.0.2,mongoose 4.8.6和node js v7.2.0
上测试了这个import * as bcrypt from 'bcrypt';
import * as mongoose from 'mongoose';
const user_schema = new mongoose.Schema({
email: { type: String, required: true },
password: { type: String, required: true },
})
mongoose.connect('mongodb://localhost:27017/test', function(err,db){
if (!err){
console.log('Connected to /localhost!');
} else{
console.dir(err);
}
});
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();
});
});
var MongoUser = mongoose.model('collectionName', user_schema);
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)
});
这是我的文件。
{ "_id" : ObjectId("58c7360e976e543af0667039"), "email" : "test@test.com", "password" : "$2a$10$h06qq1mhTCzlP5rN6.nEW.DZSlsXzU5gsAK/lShi7NOtvG6qEvqSa", "__v" : 0 }
控制台日志:
{ _id: 58c7360e976e543af0667039,
email: 'test@test.com',
password: 'testp@$$word' }
(node:15088) DeprecationWarning: Mongoose: mpromise (mongoose's default pro
Connected to /localhost!
$2a$10$h06qq1mhTCzlP5rN6.nEW.DZSlsXzU5gsAK/lShi7NOtvG6qEvqSa
callback fired