【问题标题】:Mongoose Setters only get called when create a new doc?Mongoose Setters 只有在创建新文档时才会被调用?
【发布时间】:2015-01-28 12:47:26
【问题描述】:

我使用 Mongoose getter 和 setter 我最近发现 setter 仅在我创建新文档 (UserSchema.create...) 时适用,但不会调用 setter 进行更新 (UserSchema.findByIdAndUpdate...)。我是对的还是我错过了什么。如果我是对的,是否有更新的二传手?

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

谢谢。

更新

我发现了 git 问题:https://github.com/LearnBoost/mongoose/issues/751,这意味着这是预期的行为。不确定我是对的。

【问题讨论】:

    标签: javascript node.js mongoose


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      找到了一个很好的方法来封装来自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 );
            }
          }
        });
      }
      

      (这确实属于注释,但答案允许更好的代码格式)

      【讨论】:

        猜你喜欢
        • 2015-10-13
        • 1970-01-01
        • 2021-03-21
        • 1970-01-01
        • 2017-09-24
        • 1970-01-01
        • 2021-12-29
        • 2016-06-22
        • 2016-01-13
        相关资源
        最近更新 更多