0

I am wondering what is exactly the difference in the following scenario. We have Posts which are created by users and therefore consist of a field userId in addition to the field postContent. I can now think of two possible solutions:

  1. Having a simple top-level collection Posts where each Post is a document and a separate Users top-level collection where each user is represented by a document.

enter image description here

  1. Having a Users top-level collection and a subcollection UserPosts under each user document.

enter image description here

Two possible queries:

  1. Give me all posts of user xyd. Could be done with solution 1 by asking for all documents in the collection Posts where userId == 'xyd'. Could also be done with solution 2 by asking 'get all documents under subcollection of user-doc with the id 'xyd''

  2. Give me all posts with the word 'Cats' in them. Shouldn't this also be possible with both solutions? Solution one is a basic query and solution 2 by just making a groupcollection query over the field where postContent >= 'Cats'?

Do I forget anything? Or are these two solutions both valid? If both are valid, in which scenario I just described is correct?

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
SRel
  • 383
  • 1
  • 11
  • With nosql databases like Firestore, the "correct" choice is the one that satisfies the queries for your app. There could be any number of "correct" solutions for data modeling in general - pick the one you prefer that also works within the constraints of the database system. – Doug Stevenson Feb 26 '23 at 18:39

1 Answers1

1

There is no "perfect", "the best" or "the correct" solution for structuring a Cloud Firestore database. In the NoSQL world, we are usually structuring a database according to the queries that we want to perform. So if one of the solutions you found works, then you should go ahead with it.

  1. Yes, that is correct. Both schemas can be queried to return the post of a single user.

  2. Yes, for the first solution, you only need to simple query, while when using the second solution, a collectionGroup query is required.

No, it's up to you to choose whether to use one solution over the other.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193