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
对象,以便它可以设置salt
和hash
属性?
呵呵。当然从来不知道。但果然,它的工作!对于阅读本文的其他人,我在这里阅读了更多关于[这里](https://www.nczonline.net/blog/2013/09/10/understanding-ecmascript-6-arrow-functions/)的答案。 – Jacob