我为这样的用户创建了一个模式:
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)
然后我试图使用两种方法更改密码:
工作很好
User.findById('userId ..',function(err,user){user.password ='456'; user.save(cb);})
为什么这种方法不起作用?
User.findByIdAndUpdate('userId',{$ set:{password:'456'}},cb)
发生这种情况是因为Mongoose在findByIdAndUpdate()操作中不应用以下任何内容:
来自文档:
如果您需要这些功能,请使用首先检索文档的传统方法.
Run Code Online (Sandbox Code Playgroud)Model.findById(id, function (err, doc) { if (err) .. doc.name = 'jason borne'; doc.save(callback); })