Mongoose虚拟字段未更新

yio*_*xir 3 mongoose node.js

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

    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');
};
Run Code Online (Sandbox Code Playgroud)

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

  1. 工作很好

    User.findById('userId ..',function(err,user){user.password ='456'; user.save(cb);})

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

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

vic*_*ohl 5

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

  • 默认
  • 制定者
  • 验证
  • 中间件

来自文档:

如果您需要这些功能,请使用首先检索文档的传统方法.

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