0

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?

0

2 Answers 2

2
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
        }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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.