我試圖創建數據庫對象陣列控制流程:的Node.js:用foreach
我已經實體「組」至極的hasMany「設備」,我想創建數組白衣所有組以及每個組的他的設備列表:
[
{
"group_id": 「1」,
"name": 「My_group」,
"devices_list": [1, 2, 18]
},
{
"group_id": 「2」,
"name": 「My_second_group」,
"devices_list": [3, 24]
}
]
我試過幾種方法是這樣的:
Group.all(function (err, groups) {
var resJson = {};
groups.forEach(function(group, index){
group.devices(function(err, devices){
resJson[index] = group;
console.log(devices);
resJson[index].devices_list = devices;
//End of the loop
if (index == groups.length -1){
send({code: 200, data: resJson});
}
});
});
});
編輯1:
我想這樣太:
var resJson = {};
groups.forEach(function(group, index){
group.devices(function(err, devices){
resJson[index] = group;
resJson[index].devices_list = [];
devices.forEach(function(device,index2){
resJson[index].devices_list.push(device);
});
//End of the loop
if (index == groups.length -1){
send({code: 200, data: resJson});
}
});
});
但最後,我resJson只包含空組(不包括相關設備組),另一組是不可見的。因此,我的devices_list全部爲空,而console.log(設備)顯示設備。
似乎在處理非空組之前處理「發送」指令。
這樣做的方法是什麼?
謝謝您的時間
這個*不應該是發生了什麼,但我很好奇,如果它是'resJson [index] .devices_list = devices;'line - 你是否嘗試過遍歷設備並將它們添加到設備列表中以看看這是否會改變你的回報?另外,你的'resJson'是一個對象,而不是像你的目標JSON那樣的數組。 –
感謝您的關注,我試過這個,我編輯了我的帖子。 – igor