0

I want to delete data older than 2 hours. I tried another SO answer but it did not solve my problem.

https://stackoverflow.com/a/32012520/2872091

Now, let me show my code and firebase structure

Firebase Structure:

image1

Index.js:

const functions = require('firebase-functions');
exports.deleteOldItems = functions.database.ref('Room/English/{pushId}')
.onWrite(event => {

  var ref = event.data.ref.parent; // reference to the items
  var now = Date.now();
  var cutoff = now - 2 * 60 * 60 * 1000;
  var oldItemsQuery = ref.orderByChild('time').endAt(cutoff);
  return oldItemsQuery.once('value', function(snapshot) {
    // create a map with all children that need to be removed
    var updates = {};
    snapshot.forEach(function(child) {
      updates[child.key] = null
    });
    // execute all updates in one go and return the result to end the function
    return ref.update(updates);

  });
});

Then, I deployed this js file to my firebase.

firebase deploy --only functions

It is deployed successfully, terminal said "Deploy complete!". And I can see deleteOldItems function in Firebase functions.

As a result, my structure and code is like this. And nothing changed when a new data is added to Room/English node. Data (older than 2 hours) in this node is not deleted. How can I solve the problem? What is my mistake?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
gurkan stack
  • 413
  • 1
  • 15
  • 43
  • 1
    The signature for Cloud Functions has change. I updated my original answer, and will close your question against that again. Note that this change is documented here: https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database and that the sample repo is linked is also updated: https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database. – Frank van Puffelen Jul 12 '18 at 13:28
  • Thank you very much, Mr Puffelen. You solved my problem :) Have a nice day! – gurkan stack Jul 12 '18 at 14:04

1 Answers1

0
exports.deleteOldItems = functions.database.ref('/path/to/items/{pushId}')
.onWrite(event => {
  var ref = event.data.ref.parent; // reference to the items
  var now = Date.now();
  var cutoff = now - 2 * 60 * 60 * 1000;
  var oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff);
  return oldItemsQuery.once('value', function(snapshot) {
    // create a map with all children that need to be removed
    var updates = {};
    snapshot.forEach(function(child) {
      updates[child.key] = null
    });
    // execute all updates in one go and return the result to end the function
    return ref.update(updates);
  });
});