Guim
Guim

Reputation: 678

Not getting a return object from a MySQL query in NodeJS

I'm making a logging system in NodeJS with MySQL DB. First I do the connection like this:

const con = mysql.createConnection({
  host     : 'localhost',
  user     : 'dbuser',
  password : 'dbpass',
  database : 'dbname',
  port     : 3306,
  multipleStatements : true
});

Then when I do a query to get users data I do the following query.

var user;
con.query('SELECT * FROM users WHERE email = ?', email, function(err, rows) {
    if (err) throw err;
    else {
       user = rows[0];
    }
});

But when I finally compare any of the fields of the user returned I get an error:

if (tools.hashPassword(password) == user.hash) {
    // Do stuff
}

The error is TypeError: Cannot read property 'hash' of undefined. Any suggestion?

Upvotes: 0

Views: 75

Answers (2)

Slawomir Wozniak
Slawomir Wozniak

Reputation: 518

The fact is that you are getting the result, but it is asynchronous. Therefore at the time you check for user's property hash, the object itself has not loaded yet. You should put your comparison in the callback like this:

con.query('SELECT * FROM users WHERE email = ?', email, function(err, rows) {
  if (err) throw err;
  else {
     if (tools.hashPassword(password) === rows[0].hash) {
        // Do stuff
     }
  }
});

// This stuff happens usually BEFORE the query's callback,
// due to Node.js asynchronous nature

Upvotes: 0

ponury-kostek
ponury-kostek

Reputation: 8060

con.query("SELECT * FROM users WHERE email = ?", email, function (err, rows) {
    if (err) {
        throw err;
    } else {
        if (!rows.length) {
            throw new Error("User not found");
        }
        const user = rows[0];
        if (tools.hashPassword(password) == user.hash) {
            // Do stuff
        }
    }
});

Upvotes: 2

Related Questions