英文:
Firestore: Having a subcollection per user or only a toplevel-collection?
问题
-
在以下情景中,我想知道确切的区别。我们有“帖子”由用户创建,因此除了字段“postContent”外,还包括字段“userId”。
我现在可以考虑两种可能的解决方案:
-
拥有一个简单的顶层集合“帖子”,其中每个帖子是一个文档,以及一个单独的顶层集合“用户”,其中每个用户由一个文档表示。
-
拥有一个“用户”顶层集合以及每个用户文档下的子集合“用户帖子”。
两种可能的查询:
-
给我用户xyd的所有帖子。可以通过方案1来完成,通过请求集合“帖子”中的所有文档,其中“userId == 'xyd'”。也可以通过方案2来完成,通过请求“获取用户文档子集合中的所有文档,该子集合的ID为'xyd'”。
-
给我所有帖子中包含单词'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:
- Having a simple top-level collection
Posts
where each Post is a
document and a separateUsers
top-level collection where each user
is represented by a document.
- Having a
Users
top-level collection and a subcollectionUserPosts
under each user document.
Two possible queries:
-
Give me all posts of user xyd. Could be done with solution 1 by asking for all documents in the collection
Posts
whereuserId == 'xyd'
. Could also be done with solution 2 by asking 'get all documents under subcollection of user-doc with the id 'xyd'' -
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 的世界中,通常是根据我们想执行的查询来构建数据库的结构。因此,如果你找到的解决方案之一有效,那么你应该继续使用它。
-
是的,这是正确的。两种模式都可以查询以返回单个用户的帖子。
-
是的,对于第一种解决方案,只需要进行简单的查询,而在使用第二种解决方案时,需要进行 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.
-
Yes, that is correct. Both schemas can be queried to return the post of a single user.
-
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论