如何仅从 Firebase 获取没有现有数据的新数据?

mix*_*mix 5 javascript firebase

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

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

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

Dav*_*ast 7

您需要包含一个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 
});
Run Code Online (Sandbox Code Playgroud)

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

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