Jakub Szlaur
Jakub Szlaur

Reputation: 2132

Firebase: how to delete range of items inside node based on timestamp keys?

My Firebase database data looks like this:

enter image description here

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

Console:

enter image description here

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

Upvotes: 0

Views: 126

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599581

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

Upvotes: 1

Related Questions