I have a buildings database with a user table, who can have multiple buildings. I have written a route which receives a user id and sends back details of all the buildings that are registered to that user. Response includes Buildings -> Floors -> Rooms.
Debugging the code gives me valid data returning on every query, but the final response is always null. I know there is some asynchronous issue here, can't seem to figure out the solution.
var rooms = []
var buildings_info = { Buildings:[] }
var floor_response = { Floors: [] }
var query = "Select Building_Id, Building_Address from Buildings WHERE ?? = ?";
var table = ["User_Id", user_id];
query = mysql.format(query, table);
connection.query(query, function(error, data){
for(let k=0; k<data.length; k++)
{
floor_response = { Floors: [] }
var query2 = "Select Floor_Id, Floor_Name from Floors WHERE ?? = ?";
var table2 = ["Building_Id", data[k].Building_Id]
query2 = mysql.format(query2, table2);
connection.query(query2, function(error, data2){
for(let l=0; l<data2.length; l++)
{
var room_response = { Rooms : [] }
var query3 = "Select Room_Id, Room_Name from Rooms where ?? = ?";
var table3 = ["Floor_Id", data2[l].Floor_Id]
query3 = mysql.format(query3, table3);
connection.query(query3, function(error, data3){
for(let m=0; m<data3.length; m++)
{
debug("for 3: "+data3[m].Room_Name)
room_response.Rooms.push({"Room_Id":data3[m].Room_Id, "Room_Name":data3[m].Room_Name})
debug("Rooms Data: "+JSON.stringify(room_response))
}
})
floor_response.Floors.push({"Floor_Id":data2[l].Floor_Id, "Floor_Name":data2[l].Floor_Name, "Rooms":room_response})
}
})
buildings_info.Buildings.push({"Building_ID":data[k].Building_Id, "Building_Address":data[k].Building_Address, "Floors":floor_response})
}
reply({"Buildings":buildings_info})