我使用Mongoose getter和setter我最近发现setter仅在我创建新doc(UserSchema.create ...)时适用,但setter不会被调用更新(UserSchema.findByIdAndUpdate ...)。我是对的还是我错过了什么。如果我是对的,是否有更新的setter?
(http://mongoosejs.com/docs/2.7.x/docs/getters-setters.html
感谢。
已更新
我发现git问题:https://github.com/LearnBoost/mongoose/issues/751,这意味着这是预期的行为。不确定我是对的。
答案 0 :(得分:1)
发现我不应该使用findByIdAndUpdate,而应该查询对象,编辑并保存。
答案 1 :(得分:0)
找到了一个很好的方法,它封装了https://groups.google.com/forum/?fromgroups=#!topic/mongoose-orm/8AV6aoJzdiQ:
function findByIdAndSave( model, id, data, next ){
model.findById( id, function( err, doc ) {
if( err ){
next( err, null );
} else {
if(! doc ){
next( new Error("Object to save not found"), null );
} else {
// There must be a better way of doing this
for( var k in data ){
doc[k] = data[k];
}
doc.save( next );
}
}
});
}
(这确实属于评论,但答案允许更好的代码格式化)