4
votes

Real Time x Firestore database structure

System structure posts in Real Time:

Posts
--ID_USER_1
----IdPost1
------Date
------Image
---IdPost2
------Date
------Image
---IdPost3
------Date
------Image
--ID_USER_2
----IdPost1
------Date
------Image
---IdPost2
------Date
------Image
---IdPost3
------Date
------Image

Post system model in RealTime. To structure in the Firestore, it could look something like this:

Post
--ID_POST1
----Id_user1
----Image
--ID_POST2
----Id_user2
----Image

From what I understand in Firestore has the constraints of collections, because when converting to the same structure of Real Time, it would not work because we can not have two collections like: mDB.collection ("Posts").collection().

What is the best way to structure a posting system between users?

Thank you!!

1

1 Answers

3
votes

You are correct that in Cloud Firestore you have to alternate between documents and collections, but I don't believe that will be a problem for your data structure.

For instance you could have:

  - `posts` [collection]
    - `ID_USER_1` [document]
      - `posts` [subcollection]
         - `ID_POST_1` [document]
           - `Date` [field]
           - `Image` [field]
         - `ID_POST_2` [document]
           - `Date` [field]
           - `Image` [field]

So to get all the posts for a user you could do:

db.collection('posts').doc('user1234').collection('posts').get()

// OR

db.collection('posts/user1234/posts').get()

Since Cloud Firestore also has fast and powerful queries, you could also store all of your posts in one top-level posts collection and store UserId as a property of the post:

  - `posts` [collection]
     - `ID_POST_1` [document]
       - `UserId` [field]
       - `Date` [field]
       - `Image` [field]
     - `ID_POST_2` [document]
       - `UserId` [field]
       - `Date` [field]
       - `Image` [field]

And then to get all of the posts for a user you could do:

db.collection('posts').where('UserId', '==', 'user1234')