2016-04-19 5 views
0

私はプラントと呼ばれる私のコレクションにデータセットをロードしました。ここでは植物の例です:私は私のコレクションを更新する必要がMeteorは関数からMongodbデータを操作します

{ 
"_id": "zGdXzfFTAzhrhCvqE", 
"Plant": "Carrot", 
"Companions": ["Beetroot", "Dandelion", "Rose"] 
} 

ので、各コンパニオンは、(_idを持つ)レコードですので、最初の「私は仲間がすでに_idを持っているかどうかを確認する必要がありますが、私ができます構文が正しいと思われる。

//why does'nt this work? 
    var com = Plants.find({"Plant": "Thyme"}); 
    console.log("id: " + com._id); //returns undefined, even though it exists in the collection 

    //this works 
    Plants.find({}).forEach(function(plant){ 
    var companions = plant.Companions; 
    console.log(companions[0]); //prints out the first plantname in the array 

    //here I need to check if the plant is already in the collection 
    for(var i = 0; i < companions.length; i++){ 
     var com_plante = Plants.findOne(companions[i]); 
     //this writes out undefined 
     console.log("com_plante: " + com_plante._id + " " + com_plante.Plant); 
    } 
    } 

構文にはどのような問題がありますか?代わり

答えて

1

使用findOne

var com = Plants.findOne({"Plant": "Thyme"}); 

findOneは、セレクタに一致する単一のデータ項目を返します。逆にfindは、カーソルを返します。これは、一致する項目を反復処理します。明らかに、カーソル自体は単一項目と同じプロパティを持っていません。カーソルは、fetch()メソッドを介して項目の配列に変換できます。

+0

ありがとうございました。私はまだ別の初心者です... – Heidi

0

(ループ内)あなたの2番目の検索は、文字列に基づいていますが、_idで検索するための速記を使用している:

var com_plante = Plants.findOne(companions[i]); 

.find()または.findOne()彼らは唯一の_idをチェックする単一のスカラーの引数を参照してくださいマッチのキー。

用途:

var com_plante = Plants.findOne({Plant: companions[i]}); 
関連する問題