0

model example

I want to create a database model for posts like the above image.

posts(collection) > categories(document) > c1(collection) > post_id(document) > post_data

In that case if I perform any queries like whereEqualTo or whereLessThan on c1 collection it works fine.

But in the other case,

posts(collection) > all(document) > post_id(collection) > post_data

In that case I want to perform queries on all, but I can't because it's a document.

So is there any ways to add a subcollection to a collection without adding document or adding a dummy document/collection like following is the only way to do it?

posts(collection) > all(document) > xyz(collection) > post_id(document) > post_data

Need help :(

Bucky
  • 1,116
  • 2
  • 18
  • 34
  • We are usually structuring a Firestore database according to the queries that we want to perform. What are those queries? – Alex Mamo Nov 15 '20 at 12:41
  • Query is kind of similar to the "wrap-around" section of the answer https://stackoverflow.com/a/46801925/8207701. Using cloud functions I'll get random posts (one week old limit) from user's preferred categories and "all" section, mix it up and then send it to client. – Bucky Nov 15 '20 at 13:54
  • @AlexMamo I can also achieve what I want if I use different root collections for categories and all posts or use a dummy collection name like the last mentioned code. But as a beginner I just want to know if there're any cleaner ways to model it. – Bucky Nov 15 '20 at 13:57

1 Answers1

2

It is impossible for now, you can only add documents to a collection. Your solution may be to restructure your database. Now it looks a bit strange, you double save your data.

I suggest you to do in this way:

POSTS:
     P1:
          category: c1
          data: somedata
     P2:
          category: c1
          data: somedata
     P3:
          category: c2
          data: somedata

After that you can do a query whereEqualTo("category", c1) and you will get all documents from the category c1.

Vasia Zaretskyi
  • 349
  • 3
  • 9
  • I need to perform some complex queries on both "category" and "all" collection. So using model like that isn't so flexible for me. But in the mentioned code, `POSTS > ALL > P1, P2, P3` "All" is a document. So it's not possible to use queries like whereEqualTo("category", c1) right? Or am I missing something? Thank you so much for the answer. – Bucky Nov 15 '20 at 13:42
  • Can you tell me a couple of words about complex query? What do you need to search for? I have made my answer a bit incorrect, now I have fixed it – Vasia Zaretskyi Nov 15 '20 at 14:00