Mike
Mike

Reputation: 689

Bulk-delete items from a firebase database in node.js

I'm trying to delete all nodes with a date greater than '2017-04-05' with a bulk operation with a firebase function. Can you spot what I'm doing wrong here?

The 2 nodes that should get deleted are the ones in red: enter image description here

Here's the code that is failing - can you see what's wrong? Also, I'm concerned about the performance of this (I'll only run it once in a while though). If there are millions of games in the list, should that concern me if I only run this once a day?

exports.remove = functions.https.onRequest((req, res) => {

    const deleteBeforeDate = req.query.deleteBeforeDate;

    var ref = admin.database().ref('games');

    var keysToDelete = {};
    for (var game in this.games) {

        var date = items[i]['.date'];
        if(date.value > '2017-04-05'){
            keysToDelete[game.key] = null;
        }
    }
    this.ref.update(keysToDelete);
});

Thank you very much,

Mike

Upvotes: 2

Views: 2400

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

To determine the keys to delete, you'll need to attach a listener. Since that is needed, you might as well create a query that selects the correct children and deletes only those:

var ref = admin.database().ref('games');
var deleteAfterDate = ref.orderByChild('date').startAt('2017-04-05');

deleteAfterDate.once('value').then(function(snapshot) {
  var updates = {};
  snapshot.forEach(function(child) {
    updates[child.key] = null;
  });
  ref.update(updates);
});

Upvotes: 9

Related Questions