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) {
console.log(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.
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)
break;
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) {
console.log(row);
}));
1
2
3
...