我想删除超过两小时的数据。目前,在客户端,我循环遍历所有数据并对过时的数据运行删除。当我这样做时,每次删除某些内容时都会调用 db.on('value')
函数。此外,只有在客户端连接时才会删除内容,如果同时连接两个客户端会发生什么情况?
我在哪里可以设置删除旧数据的东西?我在由 JavaScript Date.now()
创建的每个对象中都有一个时间戳。
最佳答案
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)
。当我删除每个 child 时,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
repo 中找到.
关于javascript - 删除超过 2 小时的 firebase 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37083649/