Home >Web Front-end >JS Tutorial >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(); });
Here's how it works:
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); }); });
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!