2016-09-29 8 views
0

logicfind関数に渡して、各ドキュメントで使用するにはどうすればよいですか?functionをcollection.find()に動的に指定する方法

私はプロパティ内の特定の値を持つMongoドキュメントを再帰的に検索しようとしています。私は "アルゴリズム"を定義しており、find関数にこのようにしたいと思いますが、クエリや検索、find()の読書にもかかわらず、私は運がなかった。ウラジミールMの助けを借りて

// match every node with propertyname "Reference" with the exact value "43_1" 
var logic = function(currentKey, currentValue) { 
    return (currentKey == "Reference" && currentValue === "43_1"); 
}; 

db.getCollection('metavalg').find(function() { 
    function recurSearchObj(doc) { 
     return Object.keys(doc).some(function(key) { 
      if (typeof(doc[key]) == "object" && doc[key] !== null) { 
       return recurSearchObj(doc[key]); 
      } else { 
       // invoke matching-logic 
       return logic(key, doc[key]); 
      } 
     }); 
    } 
    // search document recursively 
    return recurSearchObj(this); 
}) 

、私はコードをrearringingし、これをやってしまった:

db.getCollection('metavalg').find(function() { 
    function inspectObj(doc, logic) { 
     return Object.keys(doc).some(function(key) { 
      if (typeof(doc[key]) == "object" && doc[key] !== null) { 
       return inspectObj(doc[key], logic); 
      } else { 
       return logic(key, doc[key]); 
      } 
     }); 
    } 
    return inspectObj(this, function(currentKey, currentValue) { 
     return (currentKey == "Nummer" && currentValue === "43_1"); 
     //return (currentKey == "Navn" && /max\.? 36/i.test(currentValue)); 
    }); 
}) 
+0

データ項目のプロパティとして持っていますか? –

+0

申し訳ありませんが、あなたの質問は分かりません。 – Techek

+0

異なるデータ項目でロジックを異ならせたい場合に、そのデータ項目をカプセル化したい場合、本質的に、コレクション内の各データ項目を、同じインターフェースfind()を持つオブジェクトにする必要があります。項目。次に、コレクション上のイテレータを検索すると、内部データについて何も知らないw/o各アイテムに対してfind()を呼び出すだけでよいのです。 –

答えて

0

あなたはrecurcive検索対象にパラメータとして、論理の方法を渡すことができます。

// match every node with propertyname "Reference" with the exact value "43_1" 
var logic = function(currentKey, currentValue) { 
    return (currentKey == "Reference" && currentValue === "43_1"); 
}; 

db.getCollection('metavalg').find(function() { 
    function recurSearchObj(doc, aLogic) { 
     return Object.keys(doc).some(function(key) { 
      if (typeof(doc[key]) == "object" && doc[key] !== null) { 
       return recurSearchObj(doc[key], aLogic); 
      } else { 
       // invoke matching-logic 
       if(aLogic(key, doc[key])){ 
         // then do somthing 
       } 
      } 
     }); 
    } 
    // search document recursively 
    return recurSearchObj(this, logic); 
}); 
関連する問題