使用随机键基于嵌套值从Firebase实时数据库中删除节点
P粉558478150
P粉558478150 2024-04-03 18:10:45
0
2
347

我有一个具有以下结构的实时数据库:

"keys" :
   "randomUserId1" :
       "randomKey1" : timestamp1
   "randomUserId2" :
       "randomKey2" : timestamp2
       "randomKey3" : timestamp3
   "randomUserId3" :
       "randomKey4" : timestamp4

时间戳值是以毫秒为单位的创建时间。我现在想使用 Firebase 函数和 javascript 删除时间戳太旧的所有键。时间并不那么重要,因此删除函数可能会在数据库中其他位置的合适写入时触发。

我尝试修改示例方法删除旧的子节点,但无法理解如何使其与上述数据库结构一起使用。

如何编写 js 函数来完成上述任务?

我当然可以在“randomKey”下面添加一个键/值对(“timestamp”:时间戳),如果这样会让事情变得更容易。

P粉558478150
P粉558478150

全部回复(2)
P粉765684602

Firebase 函数(并使用 firebase-sdk)删除时间戳早于阈值的键:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.deleteOldKeys = functions.database.ref('/keys/{userId}/{key}')
  .onWrite(async (change, context) => {
    const timestampThreshold = Date.now() - (24 * 60 * 60 * 1000); // Change this to adjust the threshold
    const userId = context.params.userId;
    const key = context.params.key;
    if (!change.after.exists()) {
      // deleted key, no need to check timestamp
      return null;
    }
    const timestamp = change.after.val();
    if (timestamp 

来源参考/灵感

P粉446800329

您提供的链接基于我对删除早于2小时

要使其在您的数据结构上工作,您可以使用 orderByValue() 而不是 orderByChild("timestamp")。所以:

var oldItemsQuery = ref.orderByValue().endAt(cutoff);

要了解相关详情,请参阅 上的 Firebase 文档排序和过滤数据

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!