Home > Software design >  Firebase: how to delete range of items inside node based on timestamp keys?
Firebase: how to delete range of items inside node based on timestamp keys?

Time:11-18

My Firebase database data looks like this:

enter image description here

  • The numbers are timestamps in seconds (so the data is basically a time series).
  • I want to delete all the data OLDER then 5 seconds.
  • I am using the new Version 9 Modular JavaScript SDK's

So for example if we take that current time is 1637149389 I want to delete all the data according to the picture below: enter image description here

I tried using this code but the result is that my whole path to the data is deleted (including data not older then 5 seconds):

var timestamp = Math.round(Date.now() / 1000) - 5; //get Timestamp in Mili, convert to Seconds, and then set it 5 seconds to the past
var UID = 'uid1';

const ref = ref(
    database,
    'device_realtime/'   UID
);

var refQuery = query(
    ref,
    ...[fb.orderByKey(), fb.endAt(timestamp.toString())]
);

remove(refQuery);
  • I am little confused because when I call get(refQuery) on the same query my results are correct.
  • I only see data older then 5 seconds!

Console:

enter image description here

How would I delete only certain range of items based on their timestamp?

CodePudding user response:

To remove a node, you need to know the complete path to that node. Firebase doesn't support update/remove queries, where you pass the root reference and a condition to the database.

So you'll need to call remove() on each individual child node that you want to remove.

Something like:

get(refQuery, (results) => {
  results.forEach((snapshot) => {
    remove(snapshot.ref);
  })
})
  • Related