【问题标题】:How to structure Cloud Firestore data for an Instagram clone?如何为 Instagram 克隆构建 Cloud Firestore 数据?
【发布时间】:2021-07-16 03:30:51
【问题描述】:

我正在制作一个简单的 Instagram 克隆,其中有一个页面供用户发布图片,另一个页面用于查看其他用户发布的图片。在Cloud Firestore 我有一个collection of Users,我不知道我应该如何存储图片。我应该有一个与collection of users 处于同一级别的collection of posts,还是每个User document 都应该指向一个sub-collection of posts? 我觉得让每个User Document 指向Sub-Collection of PostsDatabase 的组织方面更有意义,但同时,我认为从Database 获得“帖子”会更加困难,而没有指定我从哪个用户那里获取子集合。

【问题讨论】:

    标签: android database firebase google-cloud-firestore


    【解决方案1】:

    在 Cloud Firestore 中,我有一组用户,但我不确定应该如何存储图片。

    我们通常根据要执行的查询来构建 Firestore 数据库。因此,如果您清楚地了解查询应该是什么,那么构建数据库模式可能会非常容易。还请记住有no "perfect", "the best" or "the correct" solution for structuring a Cloud Firestore database。您可以根据应用的用例构建结构。

    我应该拥有与用户集合处于同一级别的帖子集合,还是每个用户文档都应该指向帖子的子集合?

    Firestore 中的查询很浅,这意味着它只会从运行查询的集合中获取文档。因此,文档中是否有顶级集合或嵌套子集合并不重要,查询将始终从单个集合返回文档。

    我觉得让每个用户文档指向帖子的子集合在数据库的组织方面更有意义。

    是的,没错,如果您在每个用户文档下添加一个名为“posts”的子集合,您的架构看起来会更有条理。

    但与此同时,我认为如果不指定我从哪个用户那里获取子集合,从数据库中获取帖子会更加困难。

    没有!将其添加为顶级集合或子集合都没有区别,您将能够非常轻松地查询两者。

    假设您有一个如下所示的架构:

    Firestore-root
      |
      --- users (collection)
      |    |
      |    --- $uid (document)
      |         |
      |         --- //fields
      |
      --- posts (collection)
           |
           --- $postId (document)
                |
                --- uid: "$uid"
    

    要获取所有现有帖子,您需要使用以下 CollectionReference 对象:

    FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
    CollectionReference postsRef = rootRef.collection("posts");
    

    要获取与特定用户对应的所有帖子,您需要使用以下查询:

    Query query = postsRef.whereEqual("uid", uid);
    

    但是,如果您的数据库架构如下所示:

    Firestore-root
      |
      --- users (collection)
           |
           --- $uid (document)
           |    |
           |    --- posts (collection)
           |          |
           |         --- $postId (document)
           |
           --- $uid (document)
                |
                --- posts (collection)
                     |
                     --- $postId (document)
    

    要获取所有现有帖子,您需要使用如下所示的collection group query

    FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
    CollectionReference postsRef = rootRef.collectionGroup("posts");
    

    要获取与特定用户对应的所有帖子,您需要使用以下 CollectionReference:

    CollectionReference postsRef = rootRef.collection("users").document(uid).collection("posts");
    

    因此,从这个角度来看,哪种解决方案更好由您决定。

    【讨论】:

    • 谢谢你的详细回答,我认为对我来说最好的选择是最后一个
    • 不客气,马里奥。很高兴听到这个消息;)
    猜你喜欢
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 2021-09-22
    • 2018-04-15
    • 1970-01-01
    相关资源
    最近更新 更多