【问题标题】:How to only get new data without existing data from a Firebase?如何仅从 Firebase 获取没有现有数据的新数据?
【发布时间】:2023-04-02 11:26:01
【问题描述】:

我在 Firebase 中有一个节点不断更新日志文件中的信息。该节点是lines/lines/ 的每个子节点都来自post(),因此它具有唯一的 ID。

当客户端第一次加载时,我希望能够获取最后一个 X 条目数。我希望我会用once() 来做这件事。但是,从那时起,我想将on()child_added 一起使用,以便获得所有新数据。但是,child_added 获取存储在 Firebase 中的所有数据,并且在初始设置之后,只需要新的东西。

我看到我可以在on() 上添加limitToLast(),但是,如果我说limitToLast(1) 并且大量条目涌入,我的应用程序还会获得所有新条目吗?有没有其他方法可以做到这一点?

【问题讨论】:

  • 如果我的回答解决了您的问题,您介意将其标记为解决方案吗?如果没有,请告诉我还需要什么。

标签: javascript firebase


【解决方案1】:

您需要包含timestamp 属性并运行查询。

// Get the current timestamp
var now = new Date().getTime();
// Create a query that orders by the timestamp
var query = ref.orderByChild('timestamp').startAt(now);
// Listen for the new children added from that point in time
query.on('child_added', function (snap) { 
  console.log(snap.val()
});

// When you add this new item it will fire off the query above
ref.push({ 
  title: "hello", 
  timestamp: Firebase.ServerValue.TIMESTAMP 
});

Firebase SDK 具有排序方法orderByChild() 和创建范围startAt() 的方法。当您将两者结合起来时,您可以限制从 Firebase 返回的内容。

【讨论】:

  • 您的解决方案中的问题是,如果客户端设备未同步,new Date().getTime() 可能无法获得正确的时间戳。
【解决方案2】:

我认为@David East 的解决方案存在问题。他正在使用本地时间戳,如果客户端设备中的时间不准确,这可能会导致问题。这是我建议的解决方案(iOS Swift):

  • 使用observeSingleEvent获取完整数据集
  • 然后由reversed()以相反的顺序返回它
  • 获取最后一个时间戳,例如data[0].timestamp
  • 使用queryStarting 作为时间戳

     self._dbref.queryOrdered(byChild: "timestamp").queryStarting(atValue: timestamp+1)
         .observe(.childAdded, with: {
            snapshot in
            print(snapshot.value)
      })
    

【讨论】:

    【解决方案3】:

    你的想法是对的。 child_added 应该只为新节点调用。如果没有源代码,很难说出为什么会在 child_added 事件中获取所有数据。

    您可以查看聊天演示应用,了解它们如何加载新的聊天消息。用例听起来很相似。

    https://github.com/firebase/firechat/blob/master/src/js/firechat.js#L347

    【讨论】:

    • child_added 事件针对所有数据和然后新节点触发。所以他需要结合使用时间戳和查询来获取一个点之后的最新节点。
    【解决方案4】:

    这是临时但快速的解决方案:

    // define a boolean
    var bool = false;
    
    // fetch the last child nodes from firebase database
    ref.limitToLast(1).on("child_added", function(snap) {
        if (bool) {
            // all the existing child nodes are restricted to enter this area
            doSomething(snap.val())
        } else {
            // set the boolean true to doSomething with newly added child nodes
            bool = true;
        }
    });
    

    缺点:会加载所有子节点。

    优点:不会处理现有的子节点,只处理新添加的子节点。

    limitToLast(1) 将完成这项工作。

    【讨论】:

      猜你喜欢
      • 2017-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-08
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      相关资源
      最近更新 更多