我正在使用 firebase 制作博客应用。
我想知道数据结构的最佳实践。
据我所知,有两种情况。 (我正在使用 native react )
案例一:
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() 函数。
案例二:
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
firebase.firestore().collection(`favorites/${userID}/favoriteList`).orderBy('createdDate','desc').limit(30)
.get()
.then((snapshot) => {
snapshot.forEach((post) => {
myPostList.push(post.data())
});
});
在这种情况下,当收藏的帖子被作者修改时, 我们必须更新所有最喜欢的帖子。 (例如,如果 100 个用户将帖子收藏为收藏,我们必须更新到 100 个数据。)
(而且我不确定我们是否可以通过交易增加 favoritecount
,完全相同。)
我认为如果我们使用 firebase.batch()
,我们就可以管理它。但我认为这似乎效率低下。
看来这两种方式都不完美。你知道这个案例的最佳实践吗?
最佳答案
使用数组或 Collection Groups 怎么样? ?
解决方案 1:数组
posts
-postID
-title,content,author(userID),createdDate,favoriteCount
-[favoriters(userID)]
现在您可以通过查询“数组包含”用户 ID 的帖子来查询用户的收藏夹。您还可以修改单个帖子,而无需遍历一堆数据副本。
不过,这种方法有一个限制。文档的最大大小为 1 MiB;假设一个用户 ID 是 4 个字节,一个文档最多可以包含 250K 个收藏者。客户端还必须执行一些 O(N) 处理来添加/删除收藏夹。
解决方案 2:Collection Groups
posts
-postID
-title,content,author(userID),createdDate,favoriteCount
-favoriters {collection}
-userID
A collection group consists of all collections with the same ID. By default, queries retrieve results from a single collection in your database. Use a collection group query to retrieve documents from a collection group instead of from a single collection.
所以我们可以通过
获取用户最喜欢的帖子db.collectionGroup("favoriters").whereEqualTo("userID", <userID>).get();
要收藏一个帖子,我们只是这样做
const postsRef = db.collection("posts");
postsRef.document(<postID>).collection("favoriters").add({ "userID", <userID> });
关于javascript - firestore 数据结构的最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48651369/