猫鼬模式方法和“这个”更新属性 - NodeJS
Mongoose schema methods and "this" updating properties - NodeJS
在我的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');
};
在我的路由中,我正在尝试使用名称、电子邮件和密码设置新用户。路线如下:
// 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');
};
相关文章:
- Css order属性不't在Jquery设置时更新
- 更新属性工作不正常Meteor/MongoDB
- 阵列中的localstorage更新属性
- 数组中嵌入文档的集合更新属性
- Javascript object.defineProperties 以自动更新属性
- 使用 ajax 调用轨道更新属性
- X3DOM 更新属性
- React未从数组内的对象更新属性
- 如何使用 Ember 更新属性后滚动到 DOWN
- 如果JavaScript对象是通过引用传递的,为什么不;t更新属性值更新局部变量
- 余烬模板不更新属性变量的变化
- 如何使用jQuery更新属性?
- 更新属性指令值
- Jquery /js:脚本在输入值改变后不更新属性
- OrientDB通过JavaScript更新属性
- 猫鼬模式方法和“这个”更新属性 - NodeJS
- 不更新属性值的二传手函数
- Backbone.js正在更新属性被更改的模型
- 克隆和更新属性
- 如何在从子控制器更新属性后刷新应用程序模板