Firebase不支持帶有動態參數的查詢,例如“兩小時前”。它能,會,可以但是,對特定值執行查詢,例如“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
,而我limitToLast(1)
..當我刪除每個子程序時,Firebase將觸發一個child_added
對于新的“最后”項,直到在截止點之后沒有更多的項為止。
更新如果您想在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
回購.