Node & MySQL - connection.query inside connection.query - Object property not accessible
<p>I got a pretty awkward problem.
I create a pool, connect to the database, create a connection and query, get the results, do a bunch of stuff, then I have to create another connection and query, but actually it has to be dynamically so I loop over my Array <code>teacherHours</code> containing the data. </p>

<p>Then more Code is happening, and I have to create an extra loop, because certain elements of my <code>teacherHours</code> Array have to try multiple times to get the correct response from the upcoming query. </p>

<p>So another loop follows, which is supposed to loop as long as <code>availableHours &gt; 0</code>. Now, here is where it all goes left. </p>

<p>A buch of code happens inside the second loop, I prepare my second query, call connection.query() and inside of the callback function I prepare my third query (after doing some other stuff) and this is actually where Node kicks me out. </p>

<p>It gives me <code>TypeError: Cannot read property 'tid' of undefined</code>. <code>tid</code> needs to be accessed for my third query, so I try to access it just like I did before but Node doesn't allow it. </p>

<p>I know that the queries return useful data (rows) so it can't be a problem of querying but receiving no data. Actually I <code>console.log("the rowRIDS"+rowRIDS);</code> the result of the second query and I see that it returns 2 rows and just after that it gives me the error. </p>

<p>What is also strange to me, all the console.logs inside my my two loops are being logged, and my console.log of the second query (containing the 2 rows) are being logged after the loops ran through, since the queries are nested shouldn't the returned 2 rows and the error appear within the first iteration of the loop, since the code should access the second query at that point. </p>

<p>BTW, I've tried to set a hardcoded number instead of the <code>tid</code> just to get the next property <code>datum</code> to be an error. I kind of got a feeling as if the variable teacherHours is out of scope, but it is supposed to be a global variable.</p>

<p>To get a better feeling of what I'm talking about I copied the code and uncommented all the javascript code, where I populate and calculate stuff. Any help would be really great, its been almost 7 hours of try &amp; error without any luck. Thank You!</p>

<pre><code> pool.getConnection(function(err, connection){
  if (err) throw err;

  connection.query('SELECT * FROM teachers_teaching_tbl WHERE fwdid = 1 ', function(err, rows, fields) {  
    if (err) {
      console.error('error querying: ' + err.stack);
      return;
    } 
    rowArray=rows;
    console.log(rowArray);
    // 
    // HERE HAPPENS
    // A LOOOOT OF STUFF
    // 
    // AND teacherHours IS BEING POPULATED
    // 
    // THEN COMES A FOR LOOP 
    for(var i=0; i&lt;teacherHours.length;i++){
      //
      // MORE STUFF
      //
      //AND ANOTHER LOOP
      while(availableHours&gt;0){//do{ ORIGINALLY I TRIED WITH A DO WHILE LOOP
        //
        // AGAIN A BUNCH OF STUFF
        //
        // NOW I'M PREPARING MY NEXT QUERY 
        // 
        var myQueryGetFreeRoom=" SELECT rms.rid FROM rooms_tbl as rms WHERE NOT EXISTS ( "; 
        myQueryGetFreeRoom+=" SELECT NULL FROM classes_tbl as cls  "; 
        myQueryGetFreeRoom+="  WHERE ( (cls.bis &gt; '"+bisMinus1+"' AND cls.bis &lt;= '"+realBis+"' ) OR ( cls.von &gt; '"+bisMinus1+"' AND cls.von &lt; '"+realBis+"' ) ) AND (cls.datum = '"+teacherHours[i].datum.getFullYear()+"-"+(teacherHours[i].datum.getMonth()+1)+"-"+teacherHours[i].datum.getDate()+"') AND (cls.rid=rms.rid)  )  ";
        //
        //
        connection.query(myQueryGetFreeRoom, function(err, rowRIDS, fields) { 
          if (err) {
            console.error('error querying: ' + err.stack);
            return;
          }
          roomIDs=rowRIDS;
          console.log("the rowRIDS"+rowRIDS);
          //
          // MORE STUFF 
          // HAPPENING
          //
          if(roomIDs.length&gt;0){
            //
            // PREPARING QUERY NO.3 - WHICH IS WHERE MY ERROR POINTS - TO THE USE OF tid PROPERTY
            //
            var myQueryBookClass = " INSERT INTO classes_tbl ( rid , tid , belegtAnz, datum, von , bis )  ";
            myQueryBookClass+="  VALUES ( "+Math.floor(Math.random() * roomIDs.length)+", "+teacherHours[i].tid+" , 0, '"+teacherHours[i].datum.getFullYear()+"-"+(teacherHours[i].datum.getMonth()+1)+"-"+teacherHours[i].datum.getDate()+"' , '"+bisMinus1+"' , '"+realBis+"' ) ";
            console.log("myQueryBookClass: "+myQueryBookClass);
            availableHours = 0;
            //
            // HERE WAS SUPPOSED TO FOLLOW QUERY 3 - myQueryBookClass 
            // 
            // BUT SINCE I DONT EVEN GET INSIDE HERE IT IS IN COMMENTS
            // 
            /*connection.query(myQueryBookClass, function(err, insertRows, fields){
              if(err){
                console.error('error querying: '+err.stack);
                return;
                }
              console.log("Inserted Rows: "+ insertRows);
            }); */

          } else { 
            availableHours= availableHours - 1;
            //
            // STUFF HAPPENING
            //
          } 
        });
        availableHours= availableHours - 1;  
      }//while(availableHours&gt;0); 
    //
    }

    connection.release(function(err){
              if (err){
                console.error('error disconnecting: ' + err.stack);
                return;
              }
    });
  });
});
</code></pre>