使用隨機鍵基於嵌套值從Firebase即時資料庫中刪除節點
P粉558478150
P粉558478150 2024-04-03 18:10:45
0
2
349

我有一個具有以下結構的即時資料庫:

"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學習者快速成長!