2012-10-23 38 views
-2

我使用nodejs和mongodb。將對象推送到已存在的JavaScript對象

我從下面的MongoDB的查詢字典RES:

Profile.find(search,['_id', 'username'],function(err, res) 

印刷資源的樣子:

[ 
    { 
     "username": "dan", 
     "_id": "508179a3753246cd0100000e" 
    }, 
    { 
     "username": "mike", 
     "_id": "508317353d1b33aa0e000010" 
    } 
] 
} 

我想推到每個資源的[X]另一個鍵值對:

[ 
    { 
     "username": "dan", 
     "_id": "508179a3753246cd0100000e", 
     "more info": { 
      "weight": "80", 
      "height": "175" 
     } 
    }, 
    { 
     "username": "mike", 
     "_id": "508317353d1b33aa0e000010" 
    }, 
    "more info": { 
     "weight": "80", 
     "height": "175" 
    } 
] 
} 

我已經試過:

var x=0 dic = [] while (x<res.length){ dic[x] = {} dic[x]=res[x] dic[x]["more info"] = {"wight" : weight, "height" : hight} x=x+1 } 但會被忽略,我得到

[ 
    { 
     "username": "dan", 
     "_id": "508179a3753246cd0100000e" 
    }, 
    { 
     "username": "mike", 
     "_id": "508317353d1b33aa0e000010" 
    } 
] 
} 

感謝你的幫助。

+0

(http://stackoverflow.com/editing-help) –

+0

拼不出來的身高和體重? :) x在哪裏被定義?它在哪裏遞增? – epascarello

回答

0

改爲使用for循環。

for (var x = 0, len = res.length; x < len; ++x) { ... } 

需要初始化變量x第一(var x = 0),然後將環路(++xx += 1)的每個執行後加一。

更新:

哦,好。順便說一句,你爲什麼要創建新的數組(dic)? JavaScript中的對象是通過引用傳遞的,所以如果您只是修改單個結果(res [0],res [1]),您會得到相同的結果。

dic[x] = {}; dic[x] = res[x]沒有意義,因爲您創建一個新對象({}),然後立即用對象res[x]指向覆蓋它。

試試這個:[代碼格式]

res.forEach(function (item) { 
    item['more info'] = { weight: weight, height: height }; 
}); 

console.log(res); 
+0

謝謝你的回答。這不是問題,我只是忘了寫在 – Liatz

+0

這個問題哦,看看更新。 –

+0

再次感謝。仍然'更多信息'被忽略!甚至嘗試過:item.save() – Liatz