I am the author of pg-promise .
If you have two tables: Parent → Child with a one-to-many relationship, and you want to get an array of matching Parent rows, each row extended with the children property is set to an array of matching rows from the Child table ...
There are several ways to do this, since the combination of pg-promise and promises is generally very flexible. Here is the shortest version:
db.task(t => { return t.map('SELECT * FROM Parent WHERE prop1 = $1', [prop1], parent => { return t.any('SELECT * FROM Child WHERE parentId = $1', parent.id) .then(children => { parent.children = children; return parent; }); }).then(t.batch) }) .then(data => { });
This is what we do there:
First we query the Parent elements, then match each row with the query for the corresponding Child elements, which then sets its rows to Parent and returns it. Then we use the batch method to solve the array of Child queries returned by the map method.
The problem will be solved using such an array:
[ { "parent1-prop1", "parent1-prop2", "children": [ {"child1-prop1", "child1-prop2"}, {"child2-prop1", "child2-prop2"} ] }, { "parent2-prop1", "parent2-prop2", "children": [ {"child3-prop1", "child3-prop2"}, {"child4-prop1", "child4-prop2"} ] } ]
API links: map , batch
UPDATE
See the best answer to this question: JOIN table as an array of results with PostgreSQL / NodeJS .