Yos*_*oto 6 javascript nosql firebase react-native google-cloud-firestore
我正在使用firebase创建一个博客应用程序.
我想知道数据结构的最佳实践.
据我所知,有2个案例.(我正在使用本机反应)
情况1:
posts
-postID
-title,content,author(userID),createdDate,favoriteCount
favorites
-userID
-favoriteList
-postID(onlyID)
-postID(onlyID)
Run Code Online (Sandbox Code Playgroud)
在这种情况下,例如,当我们需要获得最喜欢的帖子时.
firebase.firestore().collection(`favorites/${userID}/favoriteList`)
.get()
.then((snapshot) => {
snapshot.forEach((favorite) => {
firebase.firestore().collection(`favorites/`).doc(`${favorite.id}`)
.get()
.then((post) => {
myPostList.push(post.data())
});
});
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我们无法订购最喜欢的帖子createdDate.所以,需要对客户端进行排序.即使这样,我们也不使用limit()函数.
案例2:
posts
-postID
-title,content,author(userID),createdDate,favoriteCount
favorites
-userID
-favoriteList
-postID
-title,content,author(userID),createdDate,favoriteCount
-postID
-title,content,author(userID),createdDate,favoriteCount
Run Code Online (Sandbox Code Playgroud)
firebase.firestore().collection(`favorites/${userID}/favoriteList`).orderBy('createdDate','desc').limit(30)
.get()
.then((snapshot) => {
snapshot.forEach((post) => {
myPostList.push(post.data())
});
});
Run Code Online (Sandbox Code Playgroud)
在这种情况下,当作者修改收藏帖子时,我们必须更新所有喜爱的帖子.(例如,如果100个用户将帖子保存为收藏,我们必须更新为100个数据.)
(而且我不确定我们可以favoritecount通过交易增加,完全相同.)
我想如果我们使用firebase.batch(),我们可以管理它.但我认为这似乎效率低下.
似乎两种方式都不完美.你知道这个案子的最佳做法吗?
使用数组或集合组怎么样?
posts
-postID
-title,content,author(userID),createdDate,favoriteCount
-[favoriters(userID)]
Run Code Online (Sandbox Code Playgroud)
现在,您可以通过查询“包含数组”用户 ID 的帖子来查询用户的收藏夹。您还可以修改单个帖子,而无需遍历一堆数据副本。
但是,这种方法是有限制的。文档的最大大小为 1 MiB;假设一个用户 ID 是 4 个字节,一个文档可以包含不超过 250K 的收藏夹。客户端还必须进行一些 O(N) 处理才能添加/删除收藏夹。
posts
-postID
-title,content,author(userID),createdDate,favoriteCount
-favoriters {collection}
-userID
Run Code Online (Sandbox Code Playgroud)
集合组由所有具有相同 ID 的集合组成。默认情况下,查询从数据库中的单个集合中检索结果。使用集合组查询从集合组而不是单个集合中检索文档。
所以我们可以通过获取用户最喜欢的帖子
db.collectionGroup("favoriters").whereEqualTo("userID", <userID>).get();
Run Code Online (Sandbox Code Playgroud)
要收藏帖子,我们只做
const postsRef = db.collection("posts");
postsRef.document(<postID>).collection("favoriters").add({ "userID", <userID> });
Run Code Online (Sandbox Code Playgroud)
也许不是您问题的直接答案,但官方文档有一个示例:
使用数组、列表和集合
摘要: 在文档中以类似数组的结构存储和查询数据。
使用案例:如果您的应用需要复杂的数据对象(例如数组、列表或集),请遵循此解决方案中概述的模型。例如,在博客应用程序中,您可能想要创建一组相关帖子。
https://firebase.google.com/docs/firestore/solutions/arrays
| 归档时间: |
|
| 查看次数: |
3975 次 |
| 最近记录: |