Firebase 不支持使用动态参数的查询,例如“两小时前”。它can但是,执行特定值的查询,例如“2015 年 8 月 14 日上午 7:27:32 之后”。
这意味着您可以定期运行一段代码来清理超过 2 小时的项目当时:
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();
});
正如你会注意到的,我使用child_added
代替value
, and I limitToLast(1)
。当我删除每个子项时,Firebase 将触发child_added
对于新的“最后”项目,直到截止点之后不再有项目。
Update:如果您想在 Cloud Functions for Firebase 中运行此代码:
exports.deleteOldItems = functions.database.ref('/path/to/items/{pushId}')
.onWrite((change, context) => {
var ref = change.after.ref.parent; // reference to the items
var now = Date.now();
var cutoff = now - 2 * 60 * 60 * 1000;
var oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff);
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 ref.update(updates);
});
});
每当数据写入时,该函数就会触发/path/to/items
,所以只有在修改数据时才会删除子节点。
此代码现在也可以在functions-samples repo https://github.com/firebase/functions-samples/tree/master/delete-old-child-nodes.