删除超过 2 小时的 Firebase 数据 [英] Delete firebase data older than 2 hours
问题描述
我想删除超过两个小时的数据.目前,在客户端,我遍历所有数据并对过时的数据运行删除.当我这样做时,每次删除某些内容时都会调用 db.on('value')
函数.另外,只有当一个客户端连接时才会删除东西,如果两个客户端同时连接会发生什么?
I would like to delete data that is older than two hours. Currently, on the client-side, I loop through all the data and run a delete on the outdated data. When I do this, the db.on('value')
function is invoked every time something is deleted. Also, things will only be deleted when a client connects, and what might happen if two clients connect at once?
在哪里可以设置删除旧数据的东西?我在 JavaScript Date.now()
创建的每个对象中都有一个时间戳.
Where can I set up something that deletes old data? I have a timestamp inside each object created by a JavaScript Date.now()
.
推荐答案
Firebase 不支持带有动态参数的查询,例如两小时前".但是,它可以对特定值执行查询,例如after August 14 2015, 7:27:32 AM".
Firebase does not support queries with a dynamic parameter, such as "two hours ago". It can however execute a query for a specific value, such as "after August 14 2015, 7:27:32 AM".
这意味着您可以定期运行一段代码来清理当时超过 2 小时的项目:
That means that you can run a snippet of code periodically to clean up items that are older than 2 hours at that time:
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
,直到截止点之后没有更多项.
As you'll note I use child_added
instead of value
, and I limitToLast(1)
. As I delete each child, Firebase will fire a child_added
for the new "last" item until there are no more items after the cutoff point.
更新:如果您想在 Cloud Functions for Firebase 中运行此代码:
Update: if you want to run this code in 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
下写入数据时都会触发此函数,因此只有在修改数据时才会删除子节点.
This function triggers whenever data is written under /path/to/items
, so child nodes will only be deleted when data is being modified.
此代码现在也可在 functions-samples
repo.
This code is now also available in the functions-samples
repo.
这篇关于删除超过 2 小时的 Firebase 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!