在我的usersSchema
中,我想为我的hash
字段设置一个哈希密码。架构如下所示:
// 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');
};
在我的 route ,我尝试设置一个具有名称、电子邮件和密码的新用户。路线如下:
// routes/users.js
router.get('/setup', (req, res) => {
const user = new User();
user.name = 'Jacob';
user.email = 'jacob@gmail.com';
user.setPassword('password');
user.save()
.then((user) => {
const token = user.generateJwt();
res.json({ yourToken: token });
})
.catch((err) => {
res.json(err);
});
});
当我从路由中 console.log(user)
时,它会给出以下内容:
{ 姓名:'雅各布',电子邮件:'jacob@gmail.com' }
我知道 setPassword
方法可以创建正确的哈希值。但是,它不会将这些哈希值保存到 user
对象中。如何将 setPassword
应用于调用它的 user
对象,以便它可以设置 salt
和 hash
属性?
最佳答案
通过使用粗箭头表示法,您可以更改 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');
};
关于javascript - Mongoose 模式方法和 "this"更新属性 - NodeJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38401848/