17

How can I check if no matching found in mysql (node.js)?

mysql.query("select * from table1 where name = 'abcd'", function(error, result, field) {
    if(error) {
        exist(error); //No error
    } else if(result) {
        console.log(result);  //displays '[]'
        exist(null, result);
    } else {
        exist(null, null); //It is never execute
    }
});
function exist(error, result) {
    if(result)
        console.log("Test:"+result); //Executed and displays 'Test:'
}

My database does not contains name = 'abcd'. So, how can I check if the query does not match?

1 Answer 1

28

You're receiving an empty array ([]) as result of your query, because as you said, your database does not contain any row with name = 'abcd'.

When you do:

if (result) {
  if (result)
    console.log("Test:" + result);

, you'll enter the if, because JavaScript evaluates true for []. Take a look at this article here, that explains how JavaScript evaluates true and false values.

A better way to check if your result array is empty is to do:

if (result.length > 0) {
  if (result)
    console.log("Test:" + result);
Sign up to request clarification or add additional context in comments.

7 Comments

if (!result.length) will work perfectly fine here.
@BenFortune Agreed, since Javascript evaluates false for 0. It's just that I like that verbose way of writing code.
Shouldn't it be (if result.isArray() && result.length > 0) ?? Anyway, Ben's "negative" is better
@BenFortune It didn't work fine for me. What worked for me is if(result.length != 0) or greater than.
If result.length is greater than 0, why do you need to check for if result?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.