Okay, let's break down why this code likely isn't working as intended and how to fix it.
The main issue is within the inner forEach loop where you process the auxResult.
auxResult.rows.forEach(a => {
e.subTypes = []; // <-- PROBLEM 1
e.subTypes.push({ months: a.months.months, price: a.price }); // <-- PROBLEM 2
});
Let's look at each problem:
-
Re-initializing e.subTypes = []; on every iteration: Inside the forEach loop, for every single sub-type (a) you find for a given e.name, you are resetting the subTypes array on the e object to an empty array ([]). This means that after the loop finishes, e.subTypes will only contain the last sub-type encountered for that name. All previous sub-types found in that auxResult.rows will have been added and then immediately discarded when the array was reset in the next iteration.
-
Accessing a.months.months: Assuming your database table membership_type has a column named months which stores a value like a number (e.g., 12, 6, 3), a.months will already be that value. You are trying to access a property named months on that value (a.months), which will almost certainly be undefined or cause a TypeError. It should just be a.months.
How to Fix It:
You need to initialize the subTypes array once for each e (the main membership type) before you start iterating through its sub-types. Then, inside the forEach loop, you just push each sub-type onto that pre-initialized array.
Here's the corrected code:
let memberships = [];
let result = await pool.query(
`SELECT DISTINCT name, min_members, max_members, description, MIN(id) AS ording -- Added AS for clarity, though optional
FROM membership_type
GROUP BY name, min_members, max_members, description
ORDER BY ording;`
);
for (let e of result.rows) {
// Initialize subTypes array *once* for the current main type 'e'
e.subTypes = []; // <-- Moved this line OUTSIDE the inner forEach
let auxResult = await pool.query(
`SELECT id, months, price FROM membership_type WHERE name = $1;`,
[e.name]
);
auxResult.rows.forEach(a => {
// Push the sub-type object onto the array
// Corrected access to 'months' and 'price'
e.subTypes.push({ months: a.months, price: a.price }); // <-- Corrected this line
});
memberships.push(e);
}
res.send(memberships);
Summary of Changes:
- The line
e.subTypes = []; was moved before the auxResult.rows.forEach(...) loop.
- The access
a.months.months was corrected to a.months.
With these changes, for each main membership type found in the first query, an empty subTypes array will be created. Then, the second query will fetch all associated pricing/duration options for that name, and each one will be correctly added (pushed) to the subTypes array. Finally, the main object e (which now contains the complete subTypes array) is added to the memberships array.