Waltari
Waltari

Reputation: 1249

Nodejs node-mysql query result data type

I have trouble figuring out how to get the data from mysql Queries in the callback function. For example I have the query as follows:

mysqlConnection.query('SELECT COUNT(*) from card AS count', function (err, result) {
    if (err) {
        throw err;
    } 
    else {
        console.log(Type.of(result));
        console.log("card count is as: " + result.count);
        console.log("Card count is: " + result["COUNT(*)"]);
        console.log(result);
    }
});

This prints out:

[Function: Array]
card count is as: undefined
Card count is: undefined
[ { 'COUNT(*)': 3 } ]

What is a "[Function: Array]" datatype and how do you pick variables from it? An array of functions? Why is "result.count" undefined even though I in the query I use the AS thing.

Also how is the following query different from the one below it?

mysqlConnection.query('SELECT COUNT(*) from card AS count', function (err, rows, fields) {
});

mysqlConnection.query('SELECT COUNT(*) from card AS count', function (err, result) {
});

When do I use the other and when the other one?

Upvotes: 2

Views: 2775

Answers (2)

trex005
trex005

Reputation: 5115

The callback with function (err, rows, fields) is much more appropriate for selecting data you are working with, and rows will then be populated by an array of arrays. So, in your case rows[0]['COUNT(*)'] would be your count.

For selects with multiple rows, you can loop through the results.

As a side note, I think you meant SELECT COUNT(*) AS count from card which would then be accessible much more simply as rows[0].count

Upvotes: 3

Vamsi Prabhala
Vamsi Prabhala

Reputation: 49260

Change your query to

SELECT COUNT(*) AS count from card 

The column alias should be defined after selecting the column, not after the from.

Upvotes: 2

Related Questions