title: MySQL NodeJs - Proper way to get rows.each to work
body: <p>When I look for simple examples, everybody's style seems quite different.  I'm tried 2 different styles, and got 2 different issues.  In the code below, I have identified the source of the code and the error it gets in comments.  I comment out or uncomment out each section and run separately, but each one has it's own errors.  The "console.log(rows); " statement is showing the data, so the query itself is running and working. </p>
  
  <pre><code>// get the client
  const mysql = require('mysql2');
  const dashline = '---------------------------------';  
  
  console.log (dashline); 
  console.log ("Starting test"); 
  
  // create the connection to database
  const connection = mysql.createConnection({
    host: 'myhost',
    user: 'myuser',
    password: 'mypass',
    database: 'myDatabase'
  
  });
  
  
  console.log ("Got the database connection"); 
  
  
  query = "select ID, user_nicename, user_email from wp_users where user_login = 'admin' limit 3 ";
  
  console.log ("Starting query"); 
  
  // Attempt 1
  /*
  connection.query(query, function(err, rows, fields){
    if (err) throw err;
  
    // from: https://html5hive.org/node-js-quickies-working-with-mysql/ 
    // error: SyntaxError: Unexpected token { (on the rows.each line below) 
    rows.each(element, index) {
      console.log(element.ID+ " " + element.user_nicename);
    }
    console.log (dashline); 
    console.log ("Query End"); 
    process.exit();   // Else Node hangs and must hit cntl-break to exit 
  
  });
  */
  
  
  
  
  // Attempt 2 
  
  connection.query(query, function(err, rows, fields){
    if (err) throw err;
    console.log(rows); 
    // Roughly based on example on this page: 
    // https://datatables.net/reference/api/each()
    // TypeError: rows.each is not a function 
    rows.each( function(element, index) {
      console.log(element.ID + " " + element.user_nicename);
    });
    console.log (dashline); 
    console.log ("The end"); 
    process.exit();   // Else Node hangs and must hit cntl-break to exit 
  });
  </code></pre>