Firestore:为每个用户拥有子集合还是仅拥有顶层集合?

huangapple go评论58阅读模式
英文:

Firestore: Having a subcollection per user or only a toplevel-collection?

问题

  1. 在以下情景中,我想知道确切的区别。我们有“帖子”由用户创建,因此除了字段“postContent”外,还包括字段“userId”。

    我现在可以考虑两种可能的解决方案:

    1. 拥有一个简单的顶层集合“帖子”,其中每个帖子是一个文档,以及一个单独的顶层集合“用户”,其中每个用户由一个文档表示。

    2. 拥有一个“用户”顶层集合以及每个用户文档下的子集合“用户帖子”。

    两种可能的查询:

    1. 给我用户xyd的所有帖子。可以通过方案1来完成,通过请求集合“帖子”中的所有文档,其中“userId == 'xyd'”。也可以通过方案2来完成,通过请求“获取用户文档子集合中的所有文档,该子集合的ID为'xyd'”。

    2. 给我所有帖子中包含单词'Cats'的帖子。这不应该在两种解决方案中都可能吗?解决方案一是基本查询,解决方案二只需在具有字段“postContent”>= 'Cats'的组合集合查询上进行。

    我有遗漏什么吗?或者这两种解决方案都有效吗?如果两者都有效,那么我刚刚描述的情景中哪一个是正确的?

英文:

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.

Firestore:为每个用户拥有子集合还是仅拥有顶层集合?

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

Firestore:为每个用户拥有子集合还是仅拥有顶层集合?

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?

答案1

得分: 1

在构建 Cloud Firestore 数据库时,没有“完美的”、“最佳的”或“正确的”解决方案。在 NoSQL 的世界中,通常是根据我们想执行的查询来构建数据库的结构。因此,如果你找到的解决方案之一有效,那么你应该继续使用它。

  1. 是的,这是正确的。两种模式都可以查询以返回单个用户的帖子。

  2. 是的,对于第一种解决方案,只需要进行简单的查询,而在使用第二种解决方案时,需要进行 collectionGroup 查询。

不,选择使用哪种解决方案取决于你。

英文:

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.

huangapple
  • 本文由 发表于 2023年2月27日 00:43:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75573490.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定