【问题标题】:Mongoose virtual field not updatedMongoose 虚拟字段未更新
【发布时间】:2015-06-10 03:11:45
【问题描述】:

我为这样的用户创建了一个架构:

    var schema = new Schema({
    username: {
        type: String,
        unique: true,
        required: true
    },
    hashedPassword: {
        type: String,
        required: true
    },
    salt: {
        type: String,
        required: true
    }
});

schema.virtual('password')
    .set(function(password) {
        this._plainPassword = password;
        this.salt = Math.random() + '';
        this.hashedPassword = this.encryptPassword(password);
    })
    .get(function() { return this._plainPassword; });

schema.methods.encryptPassword = function(password) {
    return crypto.createHmac('sha1', this.salt).update(password).digest('hex');
};

然后我尝试使用两种方法更改密码:

  1. 好好工作

    User.findById('userId..', function(err, user) { 用户密码 = '456'; 用户.保存(cb); })

  2. 为什么这种方法不起作用?

    User.findByIdAndUpdate('userId', {$set: {password: '456'}}, cb)

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    发生这种情况是因为 Mongoose 没有在 findByIdAndUpdate() 操作上应用以下任何内容:

    • 默认值
    • 二传手
    • 验证器
    • 中间件

    来自docs:

    如果您需要这些功能,请先使用传统方法 正在检索文档。

    Model.findById(id, function (err, doc) {
      if (err) ..
      doc.name = 'jason borne';
      doc.save(callback);
    })
    

    【讨论】:

      【解决方案2】:

      4.0.9+ 版本的中间件支持findByIdAndUpdate()。

      CustomerSchema.pre('findOneAndUpdate', function(next, done) {
         console.log("findOneAndUpdate pre middleware!!!");
         next();
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-31
        • 2016-02-05
        • 2020-05-16
        • 2012-11-07
        • 2020-04-04
        • 2018-10-22
        • 2021-07-09
        • 2021-06-21
        相关资源
        最近更新 更多