2017-10-03 7 views
0

私はこのようになりますマングーススキーマを持っている:予想通りサブ文書配列の特定の要素をmongooseで変更したものとしてマークするにはどうすればよいですか?

let ChildSchema = new Schema({ 
    name:String 
}); 

ChildSchema.pre('save', function(next){ 
    if(this.isNew) /*this stuff is triggered on creation properly */; 
    if(this.isModified) /* I want to trigger this when the parent's name changes */; 
    next(); 
}); 

let ParentSchema = new Schema({ 
    name: String, 
    children: [ChildSchema] 

}); 

isNewものは動作しますが、私は変更さisModifiedものはいつでも親の名前の変更をトリガーされるようにchildrenの実際の配列要素をマークしたいです。私はこれを行う方法がわかりません。

私が試してみた:

ParentModel.findById(id) 
    .then((parentDocument) => { 
     parentDocument.name = 'mommy'; //or whatever, as long as its different. 
     if(parentDocument.isModified('name')){ 
      //this stuff is executed so I am detecting the name change. 
      parentDocument.markModified('children');//probably works but doesn't trigger isModified on the actual child elements in the array 
      for(let i=0; i < parentDocument.children.length; i++){ 
       parentDocument.markModified('children.'+i);//tried this as I thought this was how you path to a specific array element, but it has no effect. 
      } 
      parentDocument.save();//this works fine, but the child elements don't have their isModified code executed in the pre 'save' middleware 
     } 
    }); 

は私の質問 - どのようにあなたは彼らのisModifiedプロパティがtrueになるように修正されたサブドキュメントの特定の(またはすべての)配列要素をマークしていますか?私のプリセーブミドルウェアは正常に実行されていますが、項目のどれもisModified === trueを持っていません。

答えて

0

markModifiedの方法は子供の方でも利用できます(ただし、私はTypeScriptを使用しているので、私は与えられた入力情報で誤解していました)。

私はこれを行うのであれば:

ParentModel.findById(id) 
    .then((parentDocument) => { 
     parentDocument.name = 'mommy'; //or whatever, as long as its different. 
     if(parentDocument.isModified('name')){ 
      for(let child of parentDocument.children){ 
       child['markModified']('name'); 
      } 
      parentDocument.save(); 
     } 
    }); 

をそれは動作します。私がしようとした場合、次のように修正されたばかりの子供自身をマークすることに注意してください:

child['markModified'](); 

私はエラーを取得する:

MongoError: cannot use the part (children of children.{ name: 'theName'}) to traverse the element <bla bla bla> 

は、私はそれがそうである理由は分からないが、それはしていません問題は、私のケースでは、いくつかの特定のフィールドが変更されているとマークされていることは問題ありませtraverseエラーが表示される理由を知ってうれしいですが、私の問題は修正されました。

関連する問題