Firebase doesn't have support for queries that involve dynamic parameters like "two hours ago". However, it is capable of executing a query for a specific value, such as "after August 14th, 2015 at 7:27:32 AM".
This means you can periodically run a block of code to tidy up items that are older than 2 hours at that particular time:
var reference = firebase.database().ref('/path/to/items/');
var currentTime = Date.now();
var timeLimit = currentTime - 2 * 60 * 60 * 1000;
var oldItems = reference.orderByChild('timestamp').endAt(timeLimit).limitToLast(1);
var eventListener = oldItems.on('child_added', function(snapshot) {
snapshot.ref.remove();
});
In this snippet, I utilize child_added
instead of value
, and apply limitToLast(1)
. As each child is deleted, Firebase will trigger a child_added
event for the new "last" item until no more items exist after the cutoff point.
Update: To execute this code in Cloud Functions for Firebase:
exports.deleteOldItems = functions.database.ref('/path/to/items/{pushId}')
.onWrite((change, context) => {
var reference = change.after.ref.parent; // reference to the items
var currentTime = Date.now();
var timeLimit = currentTime - 2 * 60 * 60 * 1000;
var oldItemsQuery = reference.orderByChild('timestamp').endAt(timeLimit);
return oldItemsQuery.once('value', function(snapshot) {
// create a map with all children that need to be removed
var updates = {};
snapshot.forEach(function(child) {
updates[child.key] = null
});
// execute all updates in one go and return the result to end the function
return reference.update(updates);
});
});
This function gets triggered whenever data is written under /path/to/items
, meaning child nodes will only be deleted during data modifications.
You can also find this code in the functions-samples
repository.