如何从Firebase获取新数据而不包含现有数据?

5

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

当客户端首次加载时,我想能够获取最后X条记录。我预计将使用once()来完成这个任务。然后,在数据更新之后,我想使用on()child_added,以便获取所有新数据。但是,child_added会获取Firebase中存储的所有数据,而我只需要新数据。

我发现可以在on()中添加limitToLast(),但如果我设置limitToLast(1)并且大量条目进来,我的应用程序是否仍然会获取所有新的记录?还有其他方法可以实现吗?


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

8

您需要包含一个时间戳属性并运行查询。

// 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返回的内容。

5
你的解决方案存在问题,如果客户端设备未被同步,new Date().getTime() 可能无法获取正确的时间戳。 - Bagusflyer

1

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

  • Using observeSingleEvent to get the complete data set
  • Then returned it in reversed order by reversed()
  • Get the last timestamp by for example data[0].timestamp
  • Using queryStarting for timestamp

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

0

1
child_added事件会为所有数据和然后新节点触发。因此,他需要使用时间戳和查询的组合来获取在某一点之后仅最新的节点。 - David East

0

这里有一个临时但快速的解决方案:

// 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) 将完成工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接