Home > database >  NodeJS - How can I check if a MySQL result is undefined/empty?
NodeJS - How can I check if a MySQL result is undefined/empty?

Time:09-16

Does anyone know how to check if a NodeJS MySQL result is null/empty? What I'm trying to do is (very succinctly explained) to check if result 5 is empty or not, and if it's not, then execute an action (console.log in this case).

This is the code without all the details, to simplify things, but when executing it I get that "result" is not defined

           con.query("SELECT tag, message FROM list1", function (err, result) {
            if (err) {
              console.log('Error: '   err)
            }
          });
        
          if(!result[5] == undefined) {
              console.log('Result 5 exists')
          }

CodePudding user response:

I highly recommend you to use this pattern.

con.query('SELECT tag, message FROM list1', [info] function(err, row, fields) {
  if(err) {
    return console.log('Error1');
  } else if (!row.length) {                                                   
    return console.log('Error2');
  } else if (!row[0].something) {
    return console.log('Error3');
  }

  console.log('Works');
})

It's using a "falsy" check for row[0]. something which will return false if the value is undefined, null or an empty string. It also fixes the injection attack vector.

CodePudding user response:

In the if statement at the bottom, use typeof result[5] !== 'undefined'.

Your current method checks if the value of result[5] is equal to undefined, but will crash if result[5] does not exist. Checking the type will return 'undefined' if the variable does not exist.

edited code:

con.query("SELECT tag, message FROM list1", function (err, result) {
    if (err) {
        console.log('Error: '   err);
    }
});
    
if(typeof result[5] !== 'undefined') {
    console.log('Result 5 exists');
}
  • Related