首页  >  问答  >  正文

使用随机键基于嵌套值从Firebase实时数据库中删除节点

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

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

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

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

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

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

P粉558478150P粉558478150181 天前354

全部回复(2)我来回复

  • P粉765684602

    P粉7656846022024-04-04 12:03:30

    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 < timestampThreshold) {
          // delete the key
          await admin.database().ref(`/keys/${userId}/${key}`).remove();
        }
        return null;
      });
    

    来源参考/灵感

    回复
    0
  • P粉446800329

    P粉4468003292024-04-04 00:15:52

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

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

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

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

    回复
    0
  • 取消回复