簡體   English   中英

貓鼬虛擬字段未更新

[英]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 ..',function(err,user){user.password ='456'; user.save(cb);})

  2. 為什么這種方法行不通?

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

發生這種情況是因為Mongoose在findByIdAndUpdate()操作上未應用以下任何內容:

  • 默認
  • 制定者
  • 驗證
  • 中間件

文檔

如果需要這些功能,請使用傳統的先獲取文檔的方法。

 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();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM