Remove nodes from Firebase realtime database based on nested values ​​using random keys
P粉558478150
P粉558478150 2024-04-03 18:10:45
0
2
487

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粉558478150
P粉558478150

reply all(2)
P粉765684602

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 

Source Reference/Inspiration

P粉446800329

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template