search

Home  >  Q&A  >  body text

Remove nodes from Firebase realtime database based on nested values ​​using random keys

I have a live database with the following structure:

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

The timestamp value is the creation time in milliseconds. I now want to use Firebase functions and javascript to delete all keys with timestamps that are too old. Timing is not that important, so the delete function may trigger on a suitable write elsewhere in the database.

I tried modifying the example method to delete old child nodes but can't understand how to make it work with the above database structure.

How to write js function to complete the above task?

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

P粉558478150P粉558478150229 days ago434

reply all(2)I'll reply

  • P粉765684602

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

    Firebase function (and using firebase-sdk) removes keys with timestamps older than the threshold:

    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

    reply
    0
  • P粉446800329

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

    The link you provided is based on my deletion earlier than 2 hours

    To make it work on your data structure, you can use orderByValue() instead of orderByChild("timestamp"). so:

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

    To learn more, see the Firebase documentation on Sorting and Filtering Data.

    reply
    0
  • Cancelreply