0

I have a realtime database with following structure:

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

The timestamp values are createdtime in milliseconds. I now want to delete all keys where timestamp is too old, using Firebase function and javascript. Timing is not that important, so the delete function may trigger on a suitable write somewhere else in the database.

I have tried modifying the example method delete old child nodes, but cannot understand how to make it work with above database structure.

How could I write a js function to accomplish above?

I could of course add a key/value pair ("timestamp" : timestamp) below "randomKey", if that makes things easier.

2 Answers2

0

Firebase function (and using firebase-sdk) that deletes keys with timestamps that are older than a threshold value:

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;
  });

Source Reference/Inspiration

Jishan Shaikh
  • 1,572
  • 2
  • 13
  • 31
0

The link you provide is based on my answer to Delete firebase data older than 2 hours

To make it work on your data structure, you can use orderByValue() rather than orderByChild("timestamp"). So:

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

To learn more about this, see the Firebase documentation on sorting and filtering data.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you, and thank you for your inspiring answer in the provided link! However I'm not that into js and still a bit confused. In above case, should ref then be '/keys/{randomUser}'? – Patrik Christiansson May 06 '23 at 15:54
  • No, the `ref` should point to the specific user for whom you want to delete the old data. There is no way in your structure to query across all nodes of all users. See https://stackoverflow.com/questions/27207059/firebase-query-double-nested – Frank van Puffelen May 06 '23 at 16:14
  • Ah, ok, thanks. So then there is no other way then to iterate all nodes. That's good to know, so that I may rest in that solution :) – Patrik Christiansson May 06 '23 at 20:49