Returning a column with node-mysql (like fetchColumn in PDO)


Is there any way to return a single column with node-mysql? I'm looking for something analogous to fetchColumn in PDO.

For example, say I have the following query:

database.query("SELECT id FROM user", function(error, row) {

This would result in:

[{id: 1}, {id: 2}, {id: 3}, ...]

Instead, I would like:

[1, 2, 3, ...]

I can run a loop to extract the data, which is what I've been doing, but I find this coming up time and again so I'm wondering if there is a simple solution.

Problem courtesy of: David Jones


You could probably add your own function to the database class in an elegant way, but since Javascript has functional support, a non intrusive way would be to just wrap your function receiving the results in a wrapper function that removes the key;

single_value = function(fn) {
  return function(e,r) {
    for(var k in r)
    return fn(e, k === undefined ? undefined : r[k]);

That way, you can call the normal query function as;

database.query("SELECT id FROM user", single_value(function(error, row) {

Solution courtesy of: Joachim Isaksson


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.