5

有人如何创建指向 Firebase 数据的临时 URL,但数据(和 URL)将在特定时间(即 5 分钟或 15 分钟)后被销毁?

4

1 回答 1

5

根据数据的确切存储方式,有几种不同的选项可用于按时间戳删除数据。

假设数据未排序,并且您已将时间戳作为字段存储在每条记录中,那么您可以简单地从第一条记录开始读取并删除它们,直到找到要保留的记录:

<script>
var FB = new Firebase(YOUR_URL);
var childRef = FB.child( TABLE_WITH_RECORDS_TO_DELETE );
var oneWeekAgo = new Date().getTime()-1000*60*60*24*7; // one week ago

var fx = function(snapshot) { // keep a ref to this so we can call off later
   var v = snapshot.val();
   if( v.expires_on_date < oneWeekAgo ) {
      // delete the record
      snapshot.ref().remove();
   }
   else {
      // we found the first keeper, so we are done
      childRef.off('child_added', fx);
   }
}

// fetched records and test to see how old they are
childRef.on('childAdded', fx);
</script>

如果数据是按时间戳排序的,您可以按如下方式检索和删除它们:

var FB = new Firebase(YOUR_URL);
var childRef = FB.child( TABLE_WITH_RECORDS_TO_DELETE );
var oneWeekAgoMinusOne = new Date().getTime()-1000*60*60*24*7-1; // one week ago

// fetched using endAt, so only retrieving older than 1 week
childRef.endAt( oneWeekAgoMinusOne ).on('childAdded', function(snapshot) {
    // delete the record
   snapshot.ref().remove();
});
于 2012-12-24T05:39:07.930 回答