How to save and return JavaScript object with Subarray in Normalized SQL

I use postgres-node

, but I think this is a problem for anyone who has javascript objects that have subarrays that they want to store in SQL. I have javascript objects with different number (any length) of array of functions:

{ 
  name: "Ted",
  features: ['Red Hair', 'Blue Eyes']
}

      

so when I have several of them, javascript formats it like this:

[
  { 
    name: "Ted",
    features: ['Red Hair', 'Blue Eyes']
  },
  { 
    name: "Ann",
    features: ['Brown Hair', 'Blue Eyes', 'Big Smile']
  }
]

      

It's great! But how do I get this back from the database after normalization? I have normalized this in my database like this:

people

Table

+---+------------+
|id | Name       |
+---+------------+
| 1 | Ted        |
| 2 | Ann        |
+---+------------+

      

features

table

+---+--------------+
|id | feature_name |
+---+--------------+
| 1 | Red Hair     |
| 2 | Blue Eyes    |
| 3 | Brown Hair   |
| 4 | Big Smile    |
+---+--------------+

      

and people_features

connection table

+---+-----------+-------------+
|id | person_id | feature_id  |
+---+-----------+-------------+
| 1 | 1         | 1           |
| 2 | 1         | 2           |
| 3 | 2         | 2           |
| 4 | 2         | 3           |
| 5 | 2         | 4           |
+---+-----------+-------------+

      

If I do something like this:

SELECT name, feature_name
FROM people
JOIN people_features ON people_features.person_id=people.id
JOIN features ON people_features.feature_id=features.id;

      

I am getting one row for each individual person. This is not what I want.

What I get:

[
  { 
    name: "Ted",
    feature_name: 'Red Hair'
  },
  { 
    name: "Ted",
    feature_name: 'Blue Eyes'
  },
  { 
    name: "Ann",
    feature_name: 'Blue Eyes'
  },
  { 
    name: "Ann",
    feature_name: 'Brown Hair'
  },
  { 
    name: "Ann",
    feature_name: 'Big Smile'
  }
]

      

What I want:

[
  { 
    name: "Ted",
    features: ['Red Hair', 'Blue Eyes']
  },
  { 
    name: "Ann",
    features: ['Brown Hair', 'Blue Eyes', 'Big Smile']
  }
]

      

It sounds awful! Now I need to go through them and combine identical people into the object of one person. My other option seems to be making a request for people

SELECT id, name
FROM people;

      

What will be returned:

[
  { 
    id: 1
    name: "Ted"
  },
  { 
    id: 2
    name: "Ann"
  }
]

      

And then I need to loop through and make a separate SQL query for each individual?

For every person:

SELECT feature_name
FROM features
JOIN people_features ON features.id=people_features.feature_id
WHERE people_features.person_id = $1

      

($ 1 is the ID of the person I'm scrolling through)

And then I'll be back (for Ted):

[
  { feature_name: 'Red Hair' },
  { feature_name: 'Blue Eyes' }
]

      

Then I need to remove them from my objects (just get the string) and then add them to the object.

Is one of them the best way to do it? I feel that they are both very ineffective.

+3


source to share


2 answers


This should do it:



SELECT name, array_agg(feature_name)
FROM people
JOIN people_features ON people_features.person_id=people.id
JOIN features ON people_features.feature_id=features.id
GROUP BY people.id;

      

+1


source


Wao Zong's answer is wonderful. For those who are interested, here is the minimum version of what I used in my node code to get it to work with node-postgres

:



var pg = require('pg');
var config = {
    user: process.env.PG_USER || null, //env var: PGUSER
    password: process.env.DATABASE_SECRET || null, //env var: PGPASSWORD
    host: process.env.DATABASE_SERVER || 'localhost', // Server hosting the postgres database
    port: process.env.DATABASE_PORT || 5432, //env var: PGPORT    
    database: process.env.DATABASE_NAME || 'lukeschlangen', //env var: PGDATABASE
    max: 10, // max number of clients in the pool
    idleTimeoutMillis: 30000, // how long a client is allowed to remain idle before being closed
};

var pool = new pg.Pool(config)

pool.connect(function (err, client, done) {
    if (err) {
        console.log('There was an error', err);
    } else {
        client.query(
            'SELECT name, array_agg(feature_name) ' +
            'FROM people ' +
            'JOIN people_features ON people_features.person_id=people.id ' +
            'JOIN features ON people_features.feature_id=features.id ' +
            'GROUP BY people.id;',
            function (err, results) {
                done();
                console.log(results.rows); // This was exactly the array I wanted
            }
        );

    }
});

      

+1


source







All Articles