我正在使用mongoose和bcrypt-nodejs。在保存到数据库之前,我运行.pre('save')中间件,其中bcrypt在调用next之前散列用户的密码。但是,非散列密码会保存到数据库中。
这是我的代码:
用户模型:
33 userSchema.pre('save', (next: any) => {
34 var user = this;
35
36 bcrypt.hash(user.password, null, null, (err: any, hash: string) => {
37 user.password = hash;
38 next();
39 })
40 });
41
42 userSchema.methods.registerUser = function(body: any, cb: any) {
43 this.username = body.username;
44 this.email = body.email;
45 this.password = body.password;
46 cb();
47 };
用户控制器:
10 router.post('/register', (req: any, res: any) => {
11 var user = new User({});
12 user.registerUser(req.body, (err: any) => {
13 user.save(function(err: any) {
14 if (err) res.render('users/register', { page: 1, error: err.errors });
15 else console.log("User Saved!");
16 console.log(user);
17 });
18 });
19 });
控制台输出:
User Saved!
{ __v: 0,
password: 'secret',
email: 'dorian3@gmail.com',
username: 'dorian3',
_id: 57c955180ca45d5e074f5763 }
我做错了什么?