2012-07-11 9 views

答えて

18

マングースはあなたが比較を行うれるカスタムセッターを設定することができます。 pre( 'save')だけでは必要なものは得られませんが、一緒に:

schema.path('name').set(function (newVal) { 
    var originalVal = this.name; 
    if (someThing) { 
    this._customState = true; 
    } 
}); 
schema.pre('save', function (next) { 
    if (this._customState) { 
    ... 
    } 
    next(); 
}) 
+0

。ありがとう。 – smabbott

+1

私は** **バリデータで前の値にアクセスするには、この操作を行う必要がありますか?あるいは、バリデータの場合にはもっと簡単な方法がありますか? – eagor

+0

古いスレッドを復活させるための@aaronheckmann申し訳ありません私たちは、ロードバランサの背後に複数のノードのサーバーを持っている場合、私は、これは動作しませんね。 – Saurabh

12

回答は非常にうまくいきます。代替構文は、スキーマ定義とセッターをインラインでも使用することができます:

var Person = new mongoose.Schema({ 
    name: { 
    type: String, 
    set: function(name) { 
     this._previousName = this.name; 
     return name; 
    } 
}); 

Person.pre('save', function (next) { 
    var previousName = this._previousName; 
    if(someCondition) { 
    ... 
    } 
    next(); 
}); 
+0

保存時にエラーが発生した場合はどうなりますか? – R01010010

1

正直なところ、私はここに掲載の解決策を試してみましたが、私は、配列内の古い値を格納します関数を作成する必要がありました値を保存し、その差異を確認します。私は必要なものだけ

// Stores all of the old values of the instance into oldValues 
const oldValues = {}; 
for (let key of Object.keys(input)) { 
    if (self[key] != undefined) { 
     oldValues[key] = self[key].toString(); 
    } 

    // Saves the input values to the instance 
    self[key] = input[key]; 
} 

yield self.save(); 


for (let key of Object.keys(newValues)) { 
    if (oldValues[key] != newValues[key]) { 
     // Do what you need to do 
    } 
} 
関連する問題