1

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?

3
  • Did you try using a for loop to loop through all the returned results? Commented Aug 16, 2016 at 21:32
  • For some reason when I do `console.log(results.length) the result is 45 and with a for loop it counts to 45. Commented Aug 16, 2016 at 21:46
  • See my answer below, see if that helps out Commented Aug 16, 2016 at 21:55

1 Answer 1

1

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..

Sign up to request clarification or add additional context in comments.

3 Comments

Ah the stringify "screwed" me over. I was wondering how my for loop would count the exact number of symbols in the string. This was rather stupid. But I'll leave it here anyway. Thanks for pointing out my mistake.
No problem! Sometimes it just takes a second set of eyes, we've all been there lol.
To point out how your code is working, the for loop loops through all the objects in the results array and since the result array has only one object it pushes that object into the current var.

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.