DEV Community

Cover image for Firestore Data Model: Threaded Comments on Several Pages
Jonathan Gamble
Jonathan Gamble

Posted on • Updated on

Firestore Data Model: Threaded Comments on Several Pages

Here is how I would model a comment thread if you have X amount of posts that might each have separate comment threads.

getComments

getComments(parentID: string, postID: string) {
  return db.collection(`posts/${postID}/comments`)
    .where('parent', '==', parentID)
    .orderBy('createdAt', 'desc');
}
Enter fullscreen mode Exit fullscreen mode

posts/postID/comments

commentDoc - root

{
  text: 'comment contents',
  uid: 293slek2l2s,
  parent: 'root',
  createdAt: serverTimestamp()
}
Enter fullscreen mode Exit fullscreen mode

commentDoc - child

{
  text: 'comment contents',
  uid: 293slek2l2s,
  parent: 'parentID',
  createdAt: serverTimestamp()
}
Enter fullscreen mode Exit fullscreen mode

post component

<comment parent="root', post="54232k21">
Enter fullscreen mode Exit fullscreen mode

comment component

<div class="container tab">
  <if comments=getComments(parent, post)>
    <forEach comments as comment>
      {{ comment.text }}
      user: {{ comment.uid }}
      <comment parent="comment.id", post="54232k21">
    </comment>
  <endIf>
</div>
Enter fullscreen mode Exit fullscreen mode

This HTML code is highly dependent on your framework, but I wanted to give a general idea of how I would model this.

Hopefully this works for you.

I will probably implement it in my Angular Project eventually.

J

Discussion (1)