我能想到的最有效的模式是:
Firestore-root
|
--- questions (collections)
| |
| --- questionId (document)
| |
| --- questionId: "02cubnmO1wqyz6yKg571"
| |
| --- title: "Question Title"
| |
| --- date: August 27, 2018 at 6:16:58 PM UTC+3
| |
| --- comments (colletion)
| | |
| | --- commentId
| | |
| | ---commentId: "5aoCfqt2w8N8jtQ53R8f"
| | |
| | ---comment: "My Comment"
| | |
| | ---date: August 27, 2018 at 6:18:28 PM UTC+3
| |
| --- likes (colletion)
| | |
| | --- likeId (document)
| | |
| | --- userId: true
| |
| --- views (colletion)
| | |
| | --- viewId (document)
| | |
| | --- userId: true
| |
| --- tags ["tagId", "tagId"]
|
--- tags (collections)
|
--- tagId (document)
|
--- tagId: "yR8iLzdBdylFkSzg1k4K"
|
--- tagName: "Tag Name"
其中
comments
,
likes
views
大学在下面吗
questionId
where
方法,您可以简单地得到这样一个特定的问题:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
DocumentReference questionIdRef = rootRef.collection("questions").document(questionId);
questionIdRef.get().addOnCompleteListener(/* ... */);
因为对于一个问题,您可以有数百、数千甚至更多的评论、赞和视图,所以将数据存储到一个数组中对您没有帮助。根据
official documentation
:
cloudfirestore是为存储大量小文档而优化的。
例如,要获取特定问题的所有注释,可以使用以下查询:
Query query = rootRef.collection("questions/"+questionId+"comments").orderBy("date", Query.Direction.DESCENDING);
因为一个问题只能有几个标记,所以您可以简单地使用数组。要获取具有特定标记的所有问题,可以使用以下查询:
Query query = rootRef.collection("questions/"+questionId+"tags").whereArrayContains("tags", tagId);
tags
对象作为数组存储在数据库中,
document.get("tags")
将返回一个
ArrayList
array
.
如果你还想计算收藏中喜欢的数量或其他文档的数量,请看我的答案
post
.
根据您的意见:
您应该在question对象中添加likes的数量作为一个属性,然后您可以根据它来查询数据库,如下所示:
Query query = rootRef.collection("questions").orderBy("numberOfLikes", Query.Direction.DESCENDING);
根据
this
Firebase Transactions
.
第二,如果我想显示所有与数学标签相关的问题(显示所有有数学标签的问题)??
whereArrayContains
方法。您还可以将标记存储为字符串而不是id。为此,您需要更改此结构:
--- tags ["tagId", "tagId"]
--- tags ["mathematics", "chemistry"]
代码应该是这样的:
Query query = rootRef.collection("questions/"+questionId+"tags").whereArrayContains("tags", "mathematics");