Firebase不支持带有动态参数的查询,例如“两个小时前”。但是,它可以执行对特定值的查询,例如“ 2015年8月14日之后7:27:32 AM”。
这意味着,你可以定期运行的代码片段是年长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和
limitToLast(1)。当我删除每个孩子时,
Firebase会child_added为新的“最后一个”项目触发,直到截止点之后没有其他项目为止。
更新:如果你想在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仓库中使用。



