【问题标题】:Firebase database data aggregationFirebase 数据库数据聚合
【发布时间】:2017-01-04 22:40:38
【问题描述】:

我们以“Instagram-like”应用为例。

在提要中,我们收到了帖子,顶部是用户头像和姓名,下面是照片或视频,底部是最后的 cmets、点赞数和发布时间。

基本上,在客户端,我正在等待从后端获取类似

{ username: "John", avatar:"some_link", photo:"photo_url", likes:"9", time:"182937428", comments:[comments there] }

但使用 Firebase,我需要以更扁平的方式存储数据。所以数据 JSON 中会有“users”、“posts”和“cmets”。

我想如何将来自这些节点的数据聚合到某种单一对象中,这在客户端很容易使用?

或者我应该向 Firebase 询问帖子,而不是询问其中的所有用户及其所有 cmets,并在完成所有三个“请求”后进行聚合?

【问题讨论】:

    标签: firebase join firebase-realtime-database nosql


    【解决方案1】:

    您应该实现“浅”树结构,并在需要时使用引用。 这意味着对于您的应用程序中的大多数情况,您应该按原样使用该对象,确保它包含“基本数据”(在下面的示例中“聊天标题”)和“更多”信息的键(在例如,“成员”的键)。

    来自 firebase 文档 (https://firebase.google.com/docs/database/web/structure-data):

    不好

    {
      // This is a poorly nested data architecture, because iterating the children
      // of the "chats" node to get a list of conversation titles requires
      // potentially downloading hundreds of megabytes of messages
      "chats": {
        "one": {
          "title": "Historical Tech Pioneers",
          "messages": {
            "m1": { "sender": "ghopper", "message": "Relay malfunction found. Cause: moth." },
            "m2": { ... },
            // a very long list of messages
          }
        },
        "two": { ... }
      }
    }
    

    {
      // Chats contains only meta info about each conversation
      // stored under the chats's unique ID
      "chats": {
        "one": {
          "title": "Historical Tech Pioneers",
          "lastMessage": "ghopper: Relay malfunction found. Cause: moth.",
          "timestamp": 1459361875666
        },
        "two": { ... },
        "three": { ... }
      },
    
      // Conversation members are easily accessible
      // and stored by chat conversation ID
      "members": {
        // we'll talk about indices like this below
        "one": {
          "ghopper": true,
          "alovelace": true,
          "eclarke": true
        },
        "two": { ... },
        "three": { ... }
      },
    
      // Messages are separate from data we may want to iterate quickly
      // but still easily paginated and queried, and organized by chat
      // conversation ID
      "messages": {
        "one": {
          "m1": {
            "name": "eclarke",
            "message": "The relay seems to be malfunctioning.",
            "timestamp": 1459361875337
          },
          "m2": { ... },
          "m3": { ... }
        },
        "two": { ... },
        "three": { ... }
      }
    }
    

    【讨论】:

    • 我还是不明白。那么如果我得到带有“头像”、“姓名”、“年龄”的“用户”呢?我得到了带有“url”、“count”和“userId”的“post”。如何把它放在一起?为每个“帖子”手动创建一个 for-each 并将“user.avatar”和“user.name”添加到其客户端实现中?如果你有成千上万的帖子怎么办?或者我应该从用户复制数据以发布?如果用户更改名称或头像怎么办???
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    • 2019-05-10
    • 1970-01-01
    • 2012-06-25
    • 2014-10-10
    相关资源
    最近更新 更多