I'm experienced in MongoDB and I'm learning PostgreSQL. In this case I'm using Node.js with the pg library.
I have 2 tables: posts and comments. What I need to do is make a query which will return an array of posts, and each returned post should have a nested array of comments.
Now, in Mongo, I would simply store posts as a comments field which would be a nested array of objects. In PostgreSQL, what I did is I made every comment have a post_id column which references the it's parent post. My question is, how to I retrieve an array structured like the mongo example? That is, how do I return an array of posts, each post having a field called comments which would be an array of the appropriate comment rows?
Right now I'm doing a JOIN of the 2 tables, but what ends up happening is I get an array of objects which contain all the fields for the posts as well as all the fields for the comments.
What's happening now:
[
{
id: 1,
post_title: "something",
posted_at: "some date",
comment_text: "nice post",
author_id: 31
},
{
id: 1,
post_title: "something",
posted_at: "some date",
comment_text: "i dont like this post",
author_id: 4
}
]
What I want to happen
[
{
id: 1,
post_title: "something",
posted_at: "some date",
comments: [
{
comment_text: "nice post",
author_id: 31
},
{
comment_text: "i dont like this post",
author_id: 4
}
},
]