【问题标题】:Hooks in Mongoose: What is 'this'猫鼬的钩子:什么是“这个”
【发布时间】:2017-06-13 22:09:13
【问题描述】:

我是 Express 和 Mongoose 的新手。我在读这个tutorial 这是教程中的一个 sn-p,其中一个 user 被保存在数据库中。

// Execute before each user.save() call
UserSchema.pre('save', function(callback) {
  var user = this;

  // Break out if the password hasn't changed
  if (!user.isModified('password')) return callback();

  // Password changed so we need to hash it
  bcrypt.genSalt(5, function(err, salt) {
    if (err) return callback(err);

    bcrypt.hash(user.password, salt, null, function(err, hash) {
      if (err) return callback(err);
      user.password = hash;
      callback();
    });
  });
});
  1. this 到底是什么。 this 是指新的/修改过的文档还是this 是指存储在数据库中的旧文档?我想this 是新文档。那么是否有任何关键字可以访问旧文档?我认为,在最坏的情况下,由于这是预保存,我可以使用findOne 访问旧/保存的文档。还有比这种方法更好的方法吗?
  2. 这里作者正在检查密码是否已更改。所以我想isModified,比较新文档和旧文档中的给定字段,并根据修改与否返回一个布尔值。问题是,作者在保存时保存了一个哈希,但是在检查修改时,我想他应该先创建哈希,然后检查哈希是否相同。我是对的,还是我在这里遗漏了什么。

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    1 - pre 钩子在将文档保存到数据库之前被调用——因此是“pre”这个词。 this 指的是保存前的文档。它将包括您对其字段所做的任何更改。

    例如,如果你这样做了

    user.password = 'newpassword';
    user.save();
    

    然后,钩子将在插入/更新数据库中的文档之前触发

    UserSchema.pre('save', function (next) {
        console.log(this.password); // newpassword
        next(); // do the actual inserting/updating
    });
    

    2 - 编辑用户时,您可以将表单的密码输入设置为空白。空白密码输入通常意味着无需更改。如果输入了新值,则视为更改密码。

    然后,您将按如下方式更改您的架构:

    为您的密码字段添加setter

    let UserSchema = new mongoose.Schema({
        password: {
            type: String,
            // set the new password if it provided, otherwise use old password
            set: function (password) {
                return password || this.password;
            }
        }
        // etc
    });
    
    UserSchema.pre('save', function (next) {
        var user = this;
        // hash password if it present and has changed
        if (user.password && user.isModified('password')) {
            // update password
        } else {
            return next();
        }
    });
    

    使用这种方法,您可能必须使用任一例如

    var user = new User({ password: req.body.password });
    user.save();
    

    user.set({ password: req.body.password });
    user.save();
    

    不确定第一个示例是否适用于 setter。

    【讨论】:

      猜你喜欢
      • 2012-04-23
      • 2019-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-04
      • 2016-03-31
      • 2014-09-05
      • 1970-01-01
      相关资源
      最近更新 更多