0

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.

// 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 
});
NealWalters
  • 17,197
  • 42
  • 141
  • 251
  • First off do some validation on the parameters, before use check typeof rows is an object and has a length > 0, same with fields. – SPlatten Aug 16 '19 at 15:20

3 Answers3

1

The method .each for Arrays doesn't exist, you should be using .forEach(function (element, index) {...}) instead

Japsz
  • 785
  • 6
  • 14
1

Use the following:

  rows.forEach( function(element, index) {
    console.log(element.ID + " " + element.user_nicename);
  });

They are certainly similar, but there are differences. For example, "forEach" is an array method, but "$.each" can be used on any type of collection. And "forEach" is a built-in, whereas "$.each" requires loading the jQuery library.

Sayyam Kapoor
  • 145
  • 2
  • 13
  • Attempt 1 with your syntax shows: rows.foreach( function(element, index) { ^ TypeError: rows.foreach is not a function Attempt 2 shows: }); ^ SyntaxError: Unexpected token } – NealWalters Aug 12 '19 at 14:21
  • I had a comment issue causing the unexpected token, they both give "rows.foreach is not a function". I'm on 10.16.2 of NodeJs. – NealWalters Aug 12 '19 at 14:28
  • 1
    Give this a try: rows.map(e=>{ console.log(e.ID + " " + e.user_nicename); }) – Sayyam Kapoor Aug 12 '19 at 15:18
  • Yes that worked, thanks! Can you help me to understand why the others were wrong? I copied them directly from blogs. Were those blogs wrong? Or does it have to do with my version or anything else? I will read up on these as soon as I get a chance. – NealWalters Aug 12 '19 at 17:07
  • I'm sorry, I just saw it might have been a syntax error on my part. I've edited it, can you give it a try now? – Sayyam Kapoor Aug 13 '19 at 04:20
  • That works too. So which is better, .forEach or .map? I will read up on them later today hopefully. – NealWalters Aug 13 '19 at 12:42
0

Got an answer here: [https://github.com/sidorares/node-mysql2/issues/999[1]. Problem with .forEach, .each or .map is that you are inside another function which is not an async function, meaning you cannot use "await" to call another async routine.

for (let r=0; r < rows.length; ++r) {
  console.log(rows[r].ID + " " + rows[r].user_nicename);
  await UpdatePassword(connection, rows[r].ID);
}

He also provided this alternative:

One "functional" way to iterate sequentially similar to map ( imo slightly less readable then for loop ):

await rows.reduce( async (previousPromise, row) => {
  await previousPromise;
  return UpdatePassword(row.ID);
}, Promise.resolve());
NealWalters
  • 17,197
  • 42
  • 141
  • 251