-2

I have the following data structure:

enter image description here

How do I completely remove 'days' using a Cloud Function?

My current code:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

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

functions.database.ref('/days').remove(); // <- /days doesn't get removed

    });
elixenide
  • 44,308
  • 16
  • 74
  • 100

1 Answers1

2

You are returning from the function before calling remove. Try:

  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(function() {;
    return functions.database.ref('/days').remove();
  });
Michael Bleigh
  • 25,334
  • 2
  • 79
  • 85
  • What doesn't work about it? Do you get an error message? – Frank van Puffelen Jun 28 '17 at 21:03
  • @FrankvanPuffelen I don't get an error message. 'days' doesn't get removed. –  Jun 28 '17 at 21:11
  • 1
    Updated my answer. You were returning before calling remove() – Michael Bleigh Jun 28 '17 at 21:45
  • It worked! But, how do I remove /days only if it has more than 1 child? @FrankvanPuffelen What changes do I have to make? –  Jun 29 '17 at 16:13
  • You will have to modify the code to include that condition. I recommend taking a few steps back from Cloud Functions and first trying to get the same working with the regular [Firebase JavaScript SDK](https://firebase.google.com/docs/database/web/start). A jsbin if my favorite place to write such snippets. Once you have it working there, it's easy to transport it into a Cloud Function and deploy. – Frank van Puffelen Jun 29 '17 at 16:30
  • @FrankvanPuffelen I took a few back and tried to tackle the problem but I failed. So, I asked a new question here, with new code: https://stackoverflow.com/questions/44743530/node-with-more-than-1-child-is-not-getting-removed –  Jun 29 '17 at 19:31
  • @FrankvanPuffelen You will see that I added an if statement. –  Jun 29 '17 at 19:32