【问题标题】:How can I order my Firebase array according to data in another node?如何根据另一个节点中的数据订购我的 Firebase 阵列?
【发布时间】:2016-04-21 22:31:18
【问题描述】:

我在 Firebase 中有一些非规范化实体,如下所示:

projects
  -KFsomething
    name: "foo"
  -KFwhatever
    name: "bar"
users
  UID-1234
    name: "Bob"
  UID-5678
    name: "Alice"
observations
  -KFblah
    project: -KFwhatever
    user: UID-1234
    timestamp: 1234567890
  -KFrandom
    project: -KFsomething
    user: UID-5678
    timestamp: 1234567899

等等,还有其他孩子。还有其他具有类似关系的实体。我需要能够在网页上按他们最近的相关观察来显示用户、项目或其他事物的列表。所以用户将被排序为 Alice 然后 Bob,因为 Alice 有更新的观察。同样,项目将按 foo 然后 bar 排序,因为较新的观察属于 foo。

如何处理非规范化数据?决定排序顺序的参数不属于被排序的对象。我可以对数据做些什么来使其更容易,还是我需要一些多步骤的客户端查询?

【问题讨论】:

    标签: javascript firebase firebase-realtime-database


    【解决方案1】:

    在 NoSQL 中,您经常需要对数据进行建模,以允许以您想要的方式使用它。由于您希望通过用户最近的观察来显示用户,因此您应该为每个用户存储最近观察的时间戳。

    projects
      -KFsomething
        name: "foo"
        mostRecentObservationTimestamp: 1234567899
      -KFwhatever
        name: "bar"
        mostRecentObservationTimestamp: 1234567890
    users
      UID-1234
        name: "Bob"
        mostRecentObservationTimestamp: 1234567890
      UID-5678
        name: "Alice"
        mostRecentObservationTimestamp: 1234567899
    observations
      -KFblah
        project: -KFwhatever
        user: UID-1234
        timestamp: 1234567890
      -KFrandom
        project: -KFsomething
        user: UID-5678
        timestamp: 1234567899
    

    您通常会在发布新观察时写入额外信息,并进行多地点更新:

    var observation = {
        project: "-KFsomething",
        user: "UID-5678"
        timestamp: 1234567899
    };
    var updates = {};
    var key = ref.push().key();
    updates['observations/'+key] = observation;
    updates['users/'+observation.user+'/mostRecentObservationTimestamp'] = observation.timestamp;
    updates['projects/'+observation.project+'/mostRecentObservationTimestamp'] = observation.timestamp;
    ref.update(updates);
    

    看到这个很棒的blog post on client-side fan-out

    【讨论】:

    • 我自己刚刚得出这个结论。很高兴知道我在正确的轨道上。
    猜你喜欢
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2023-02-18
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多