6

I'm using array_agg to group values into an array. The output for row is:

row: anonymous { values: '{(1),(2)}' }

I'm trying to then loop through the results in Node,

row.values.forEach(... but it says values.forEach is not a function, because typeof row.values is String.

I'm using array_agg, so why is the output a string, and how can I convert it to an array?

1
  • 1
    The Postgres wire protocol represents pretty much everything as a printable string; it's up to the client driver to convert it into a native data type (int, float, boolean, etc). Arrays are relatively rare, so most drivers don't have built-in handling for them. Unfortunately, the string format is rather hard to parse; one workaround is to use array_to_json to get something more readily parseable. (Not answering, because I don't know specifically about this driver.) Commented Jan 10, 2017 at 18:32

4 Answers 4

9

I just ran into this problem too and unnest wasn't an option due to needing a fixed number of rows to be returned and I couldn't guarantee my content wouldn't contain a , or brackets which made a regex solution challenging.

I found the best solution was to use json_agg instead of array_agg. (See the documentation) This returned the results in JSON format and node automatically interpreted it as a javascript object so you can use .forEach without any conversion needed.

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

Comments

1

Can convert an array to a set of rows by using: unnest

create temp table t (name text);
insert into t values ('name1'),('name2'),('name3'),('name4');

select unnest(array_agg(name)) as aname from t

+-------+
| aname |
+-------+
| name1 |
+-------+
| name2 |
+-------+
| name3 |
+-------+
| name4 |
+-------+

Comments

0

If you're expecting integers in the array, you can use regex and loop through the matches of (\d+).

Another method is to use array_to_string and have it join using values that do not appear in the content, a newline \n for example: array_to_string(some_array_content, E'\n'), then split it later.

Once you get it into an array one way or another, forEach will work.

Also, I believe Sequelize can handle arrays: http://docs.sequelizejs.com/en/v3/api/datatypes/#array

Comments

0

Dont know about knex, but for node-postgres, you can cast the results of array_agg to an array type, i.e. ::int[] and it will return an array instead of a string:

SELECT 
  array_agg(name)::int[],
  foo_id
FROM bar 
GROUP BY foo_id;

Comments

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.