首页 > 解决方案 > Delete older firebase data

问题描述

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?

标签: javascriptfirebasefirebase-realtime-databasegoogle-cloud-functions

解决方案


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

推荐阅读