Javascript firestore数据结构的最佳实践是什么?
我正在使用firebase制作一个博客应用程序 我想知道数据结构的最佳实践 据我所知,有两种情况。 (我正在使用react native) 案例1:Javascript firestore数据结构的最佳实践是什么?,javascript,firebase,react-native,nosql,google-cloud-firestore,Javascript,Firebase,React Native,Nosql,Google Cloud Firestore,我正在使用firebase制作一个博客应用程序 我想知道数据结构的最佳实践 据我所知,有两种情况。 (我正在使用react native) 案例1: posts -postID -title,content,author(userID),createdDate,favoriteCount favorites -userID -favoriteList -postID(onlyID) -postID(onlyID) 例如,在这种情况下,当我们需要获
posts
-postID
-title,content,author(userID),createdDate,favoriteCount
favorites
-userID
-favoriteList
-postID(onlyID)
-postID(onlyID)
例如,在这种情况下,当我们需要获得最喜欢的帖子时
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())
});
});
在这种情况下,我们不能通过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
在这种情况下,当作者修改了最喜爱的帖子时,
我们必须更新所有喜欢的帖子。(例如,如果有100个用户将帖子保存为收藏夹,我们必须更新到100个数据。)
(我不确定我们是否可以通过一个事务来增加favoritecount
,完全相同。)
我认为如果我们使用firebase.batch()
,我们可以管理它。但我认为这似乎效率低下
这两种方法似乎都不完美。您知道本案例的最佳实践吗?可能不是您问题的直接答案,但官方文档中有一个例子: 使用数组、列表和集合 摘要:在文档中以类似数组的结构存储和查询数据 用例:如果你的应用程序需要复杂的数据对象,比如数组, 列表或集合遵循此解决方案中概述的模型。对于 例如,在博客应用程序中,您可能希望创建一组相关的 职位
如何使用数组或 解决方案1:阵列 现在,您可以通过查询“数组包含”用户ID的帖子来查询用户的收藏夹。您还可以修改单个帖子,而无需遍历一堆数据副本 不过,这种方法是有局限性的。文档的最大大小为1 MiB;假设用户ID为4字节,则文档中最多可以包含250K个收藏夹。客户端还必须进行一些O(N)处理来添加/删除收藏夹 解决方案2: 集合组由具有相同ID的所有集合组成。默认情况下,查询从数据库中的单个集合检索结果。使用集合组查询从集合组而不是单个集合检索文档 因此,我们可以通过
db.collectionGroup("favoriters").whereEqualTo("userID", <userID>).get();
db.collectionGroup(“favoriters”).whereEqualTo(“userID”),.get();
要喜欢一篇文章,我们只需
const postsRef = db.collection("posts");
postsRef.document(<postID>).collection("favoriters").add({ "userID", <userID> });
const postsRef=db.collection(“posts”);
postsRef.document().collection(“favoriters”).add({“userID”,});
您应该以最适合您要执行的查询的方式构造数据。@DougStevenson感谢您的响应。嗯。。。我发现是逐案的。谢谢
posts
-postID
-title,content,author(userID),createdDate,favoriteCount
-favoriters {collection}
-userID
db.collectionGroup("favoriters").whereEqualTo("userID", <userID>).get();
const postsRef = db.collection("posts");
postsRef.document(<postID>).collection("favoriters").add({ "userID", <userID> });