Peter Boomsma Peter Boomsma - 3 months ago 21
Javascript Question

Can't get value from mysql result using Express/Node

I'm working on a pluralsight module for authentication and I'm stuck at the point of actually trying to authenticate users.

connection.query('SELECT * FROM users WHERE username LIKE ?', [data.username], function (err, results) {
if (err) throw err;
var results=(JSON.stringify(results));
console.log(results);
console.log(results.password)
if(results.password === password){
var user = results;
// done(null, user);
} else {
console.log('else')
// done('Bad password', null)
}
});


I have this mysql query which looks up the record corresponding to the username and then returns an
err
or
results
. I've used
JSON.stringify
to convert the initial result:

[ RowDataPacket { id: 12, username: 'qqq', password: 'qqq' } ]


To this:

[{"id":12,"username":"qqq","password":"qqq"}]


But
results.username
and
results.password
bot are undefined. So it looks to me that the stringyfied results is an array with an object in it.

But when I do

console.log(results[0].username);
console.log(results[0].password);


They are still
undefined
. So how do I store the username/password inside a variable?

You You
Answer

Try looping through the result set like this:

for (var i = results.length - 1; i >= 0; i--) {
    var current = results[i];
    console.log(current);
}

Then if all goes well, you should be able to check each variable with: current.username etc..