【问题标题】:What is the best practice of firestore data structure?Firestore 数据结构的最佳实践是什么?
【发布时间】:2018-07-17 00:13:10
【问题描述】:

我正在使用 firebase 制作博客应用。

我想知道数据结构的最佳实践。

据我所知,有两种情况。 (我正在使用本机反应)

案例一:

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

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(),我们可以管理它。但我认为它似乎效率低下。

看来这两种方式都不完美。你知道这个案例的最佳实践吗?

【问题讨论】:

  • 您应该以最适合您要执行的查询的方式构建数据。
  • @DougStevenson 谢谢你的回应。嗯...我发现这是个案。谢谢

标签: javascript firebase react-native nosql google-cloud-firestore


【解决方案1】:

使用数组或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

集合组由具有相同 ID 的所有集合组成。默认情况下,查询从数据库中的单个集合中检索结果。使用集合组查询从集合组而不是单个集合中检索文档。

所以我们可以通过

获取用户最喜欢的帖子
db.collectionGroup("favoriters").whereEqualTo("userID", <userID>).get();

要收藏帖子,我们只需这样做

const postsRef = db.collection("posts");
postsRef.document(<postID>).collection("favoriters").add({ "userID", <userID> });

【讨论】:

    【解决方案2】:

    也许不能直接回答您的问题,但官方文档中有一个示例:

    使用数组、列表和集合

    总结:在文档中以类似数组的结构存储和查询数据。

    用例:如果您的应用需要复杂的数据对象,例如数组, 列表或集合遵循此解决方案中概述的模型。为了 例如,在博客应用程序中,您可能希望创建一组相关的 帖子。

    https://firebase.google.com/docs/firestore/solutions/arrays

    【讨论】:

      猜你喜欢
      • 2021-08-28
      • 2016-09-21
      • 1970-01-01
      • 2011-11-22
      • 2023-04-08
      • 2023-03-21
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      相关资源
      最近更新 更多