栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JavaScript删除2个小时之前的Firebase数据

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaScript删除2个小时之前的Firebase数据

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仓库中使用。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/373568.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号