猫鼬模式方法和“这个”更新属性 - NodeJS

Mongoose schema methods and "this" updating properties - NodeJS

本文关键字:更新 属性 NodeJS 这个 模式 方法      更新时间:2023-09-26

在我的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对象,以便它可以设置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');
};