skip to Main Content

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

Answers


  1. 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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search