简体   繁体   English

猫鼬的塞特犬只在创建新文档时被调用?

[英]Mongoose Setters only get called when create a new doc?

I use Mongoose getter and setter I recently found that setter only applies when I create a new doc (UserSchema.create...) but setter will not get called for update (UserSchema.findByIdAndUpdate...). 我使用Mongoose getter和setter,我最近发现setter仅在创建新文档(UserSchema.create ...)时适用,但不会调用setter进行更新(UserSchema.findByIdAndUpdate ...)。 Am I right or am I missing anything. 我是对的还是我错过了什么。 If I'm right, is there setter for update? 如果我说的没错,是否有传教士要更新?

( http://mongoosejs.com/docs/2.7.x/docs/getters-setters.html http://mongoosejs.com/docs/2.7.x/docs/getters-setters.html

Thanks. 谢谢。

UPDATED 更新

I found git issue: https://github.com/LearnBoost/mongoose/issues/751 , it means this is expected behavior. 我发现了git问题: https : //github.com/LearnBoost/mongoose/issues/751 ,这意味着这是预期的行为。 Not sure I'm right. 不确定我是对的。

发现我不应该使用findByIdAndUpdate,而应该查询对象,进行编辑和保存。

Found a nice method that encapsulates that from https://groups.google.com/forum/?fromgroups=#!topic/mongoose-orm/8AV6aoJzdiQ : 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 );
      }
    }
  });
}

(This really belongs as a comment, but the answer allows better code formatting) (这实际上是作为注释,但是答案允许更好的代码格式)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM