Javascript 删除超过 2 小时的 Firebase 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32004582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delete firebase data older than 2 hours
提问by carterw485
I would like to delete any data that is older that two hours. Currently, on the client side, I loop through all the data, and run a delete on any that is older. 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?
我想删除任何早于两个小时的数据。目前,在客户端,我遍历所有数据,并对任何较旧的数据运行删除。当我这样做时,每次删除某些内容时都会调用 db.on('value') 函数。此外,只有在客户端连接时才会删除内容,如果两个客户端同时连接会发生什么?
Where can I set up something that deletes old data? I have a time stamp inside each object created by a JavaScript Date.now().
我在哪里可以设置删除旧数据的东西?我在 JavaScript Date.now() 创建的每个对象中都有一个时间戳。
回答by Frank van Puffelen
Firebase does not support queries with a dynamic parameter, such as "two hours ago". It canhowever execute a query for a specific value, such as "after August 14 2015, 7:27:32 AM".
Firebase 不支持带有动态参数的查询,例如“两小时前”。但是,它可以对特定值执行查询,例如“after August 14 2015, 7:27:32 AM”。
That means that you can run a snippet of code periodically to clean up items that are older than 2 hours at that time:
这意味着,你可以定期运行的代码片段是年长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();
});
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.
正如您会注意到的,我使用child_added
代替value
, 和 I limitToLast(1)
。当我删除每个孩子时,Firebase 将为child_added
新的“最后一个”项目触发一个,直到截止点之后没有更多项目。
Update: if you want to run this code in Cloud Functions for Firebase:
更新:如果您想在 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);
});
});
This function triggers whenever data is written under /path/to/items
, so child nodes will only be deleted when data is being modified.
每当在 下写入数据时都会触发此函数/path/to/items
,因此只有在修改数据时才会删除子节点。
This code is now also available in the functions-samples
repo.
此代码现在也可以在functions-samples
repo 中找到。
回答by Sergio
I have a http triggered cloud function that deletes nodes, depending on when they were created and their expiration date.
我有一个 http 触发的云函数可以删除节点,具体取决于节点的创建时间和到期日期。
When I add a node to the database, it needs two fields: timestampto know when it was created, and durationto know when the offer must expire.
当我向数据库添加一个节点时,它需要两个字段:时间戳以了解其创建时间,以及持续时间以了解优惠何时必须到期。
Then, I have this http triggered cloud function:
然后,我有这个 http 触发的云功能:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
/**
* @function HTTP trigger that, when triggered by a request, checks every message of the database to delete the expired ones.
* @type {HttpsFunction}
*/
exports.removeOldMessages = functions.https.onRequest((req, res) => {
const timeNow = Date.now();
const messagesRef = admin.database().ref('/messages');
messagesRef.once('value', (snapshot) => {
snapshot.forEach((child) => {
if ((Number(child.val()['timestamp']) + Number(child.val()['duration'])) <= timeNow) {
child.ref.set(null);
}
});
});
return res.status(200).end();
});
You can create a cron job that every X minutes makes a request to the URL of that function: https://cron-job.org/en/
您可以创建一个 cron 作业,每 X 分钟向该函数的 URL 发出一次请求:https: //cron-job.org/en/
But I prefer to run my own script, that makes a request every 10 seconds:
但我更喜欢运行自己的脚本,每 10 秒发出一个请求:
watch -n10 curl -X GET https://(your-zone)-(your-project-id).cloudfunctions.net/removeOldMessages
回答by Won Jun Bae
In the latest version of Firebase API, ref() is changed to ref
在最新版本的 Firebase API 中,ref() 更改为 ref
var ref = new Firebase('https://yours.firebaseio.com/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();
});
回答by James Oliver
You could look into Scheduling Firebase Functions with Cron Jobs. That link shows you how to schedule a Firebase Cloud Function to run at a fixed rate. In the scheduled Firebase Function you could use the other answers in this thread to query for old data and remove it.
您可以查看Scheduling Firebase Functions with Cron Jobs。该链接向您展示了如何安排 Firebase 云函数以固定速率运行。在预定的 Firebase 函数中,您可以使用此线程中的其他答案来查询旧数据并将其删除。