2016-07-15 59 views
0

在我的usersSchema我想设置一个哈希密码到我的hash字段。模式如下所示:猫鼬模式方法和“这个”更新属性 - NodeJS

// models/user-model.js 

const usersSchema = new Schema({ 
    name: { 
    type: String, 
    required: true 
    }, 
    email: { 
    type: String, 
    unique: true, 
    required: true 
    }, 
    hash: String, 
    salt: String 
}, { timestamps: true }); 

usersSchema.methods.setPassword = (password) => { 
    this.salt = crypto.randomBytes(16).toString('hex'); 
    this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex'); 
}; 

在我的路线中,我尝试使用名称,电子邮件和密码设置新用户。这里的路线:

// routes/users.js 

router.get('/setup', (req, res) => { 
    const user = new User(); 

    user.name = 'Jacob'; 
    user.email = '[email protected]'; 

    user.setPassword('password'); 

    user.save() 
    .then((user) => { 
     const token = user.generateJwt(); 
     res.json({ yourToken: token }); 
    }) 
    .catch((err) => { 
     res.json(err); 
    }); 
}); 

当我console.log(user)从路由,它给了我下面的: {名称: '雅各',电子邮件: '[email protected]'}

我知道,方法尽可能地创造适当的哈希值。但是,它不会将这些散列保存到user对象中。如何将setPassword应用于调用它的user对象,以便它可以设置salthash属性?

回答

2

通过使用胖箭头符号,您正在更改this指的是setPassword,因此它不再指向用户文档。

尝试使用普通函数声明:

usersSchema.methods.setPassword = function(password) { 
    this.salt = crypto.randomBytes(16).toString('hex'); 
    this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex'); 
}; 
+0

呵呵。当然从来不知道。但果然,它的工作!对于阅读本文的其他人,我在这里阅读了更多关于[这里](https://www.nczonline.net/blog/2013/09/10/understanding-ecmascript-6-arrow-functions/)的答案。 – Jacob