2016-04-19 53 views
0

我已經在我的集合中加載了一個名爲Plants的數據集。這裏的植物的例子:流星操縱函數的Mongodb數據

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

我需要更新我的集合,使得每一個伴侶是一個記錄(有一個_id),所以首先我需要檢查,如果同伴已經有一個_id,但我可以」 t似乎得到正確的語法。

//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

你的第二個搜索是基於一個字符串,但您使用的簡寫通過_id搜索:

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

.find().findOne()看到一個標量參數,他們只檢查_id一場比賽的關鍵。

用途:

var com_plante = Plants.findOne({Plant: companions[i]});