0
我想組合兩個來自MongoDB的數組:一組聯繫對象和一組約會。未將數組添加到數組中的對象
我目前的解決方案是查詢所有聯繫人和約會,遍歷每個數組,比較電子郵件,如果他們匹配,將每個約會添加到其相應的聯繫人。
var contacts, appointments;
Contact.find(query, function(err, result1) {
if (err) {
console.log(err)
}
else {
contacts = result1;
Appointment.find({isArchived : false}, function(err, result2) {
if (err) {
console.log(err);
}
else {
appointments = result2;
for (var i=0; i<contacts.length;i++) {
contacts[i]["appointments"] = [];
for (var j=0; j<appointments.length;j++) {
if (contacts[i].email === appointments[j].owner) {
contacts[i].appointments.push(appointments[j]);
}
}
}
res.send(contacts);
}
});
}
});
聯繫人:
[{
email: "[email protected]"
}, {
email: "[email protected]"
}]
[{
email: "[email protected]",
start: "2015-01-01",
end: "2015-02-01"
}, {
email: "[email protected]",
start: "2015-02-01",
end: "2015-03-01"
}]
// Desired output
[{
email: "[email protected]",
appointments: [{
email: "[email protected]",
start: "2015-01-01",
end: "2015-02-01"
}, {
email: "[email protected]",
start: "2015-02-01",
end: "2015-03-01"
}]
}, {
email: "[email protected]",
appointments: []
}]
我知道這是一個爛攤子,我也無法預約陣列每個聯繫人添加。我只能將值賦給現有的對象鍵。
所以這真的是兩個問題:1)爲什麼我不能將數組追加到現有的聯繫人,2)什麼是更高效的解決方案?