Mongoose 虚拟字段未更新

Mongoose virtual field not updated

我为这样的用户创建了一个模式:

    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..', 函数(错误, 用户) { user.password = '456'; user.save(cb); })

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

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

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

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

来自docs

If you need those features, use the traditional approach of first retrieving the document.

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

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

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