javascript - Mongoose 模式方法和 "this"更新属性 - NodeJS

标签 javascript node.js mongodb mongoose

在我的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 对象,以便它可以设置 salthash 属性?

最佳答案

通过使用粗箭头表示法,您可以更改 thissetPassword 中所指的内容,因此它不再指向用户文档。

尝试使用常规函数声明:

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/

相关文章:

javascript - 方法 : => :delete not working and :confirm option ignored

javascript - 选择框和复选框替换

javascript - 为什么 mongoose 以 ID 作为 Buffer 而不是字符串的对象形式返回对象 ID'?

node.js - 错误 : Cannot find module 'pug'

node.js - Redis - 在事务中使用 Incr 值

python - MongoDB,批量查找返回什么

包含多个位置的 MongoDB 和 2dsphere 索引

javascript - Javascript 中的负后视正则表达式

javascript - 如何组合多个 onclick 事件/元素

mongodb - 如何在 Mongo 中计算 future 的数据库大小?