Home > Web Front-end > JS Tutorial > How to Delete Firebase Data Older Than Two Hours?

How to Delete Firebase Data Older Than Two Hours?

Susan Sarandon
Release: 2024-12-07 22:06:15
Original
757 people have browsed it

How to Delete Firebase Data Older Than Two Hours?

Delete Firebase Data Older Than 2 Hours

The Question:

To avoid latency and optimize database performance, it's important to efficiently delete outdated data. This question seeks a way to remove Firebase data that is over two hours old.

The Solution:

Firebase does not allow querying with dynamic parameters like "two hours ago." Instead, we can execute a query for a specific timestamp, such as "after a specific past date and time."

To delete old data, consider the following code snippet:

var ref = firebase.database().ref('/path/to/items/');
var now = Date.now();
var cutoff = now - 2 * 60 * 60 * 1000;
var old = ref.orderByChild('timestamp').endAt(cutoff).limitToLast(1);
var listener = old.on('child_added', function(snapshot) {
    snapshot.ref.remove();
});
Copy after login

Here's how it works:

  • Use child_added instead of value.
  • Set limitToLast(1) to ensure only the last item after the cutoff is deleted.
  • As items are deleted, Firebase triggers child_added for the next "last" item until all outdated items are removed.

For Cloud Functions for Firebase:

exports.deleteOldItems = functions.database.ref('/path/to/items/{pushId}')
.onWrite((change, context) => {
  var ref = change.after.ref.parent;
  var now = Date.now();
  var cutoff = now - 2 * 60 * 60 * 1000;
  var oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff);
  return oldItemsQuery.once('value', function(snapshot) {
    var updates = {};
    snapshot.forEach(function(child) {
      updates[child.key] = null
    });
    return ref.update(updates);
  });
});
Copy after login

This function executes whenever data is modified under /path/to/items, deleting child nodes only when they are being modified.

The above is the detailed content of How to Delete Firebase Data Older Than Two Hours?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template