Akshay Masram
Akshay Masram

Reputation: 337

Firebase Cloud Functions is deleting data immediately after write

I have implemented Firebase Cloud Functions to delete data from the Firebase database. I have a timestamp in my every child so I want to delete data when it is older than 2 hours but instead of deleting after 2 hours it is deleting child immediately after writing to the database.

This is the Cloud Functions code:

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

// Cut off time. Child nodes older than this will be deleted.
const CUT_OFF_TIME = 2 * 60 * 60 * 1000; // 2 Hours in milliseconds.

/**
 * This database triggered function will check for child nodes that are older than the
 * cut-off time. Each child needs to have a `timestamp` attribute.
 */
exports.deleteOldItems = functions.database.ref('/database/{pushId}').onWrite(async (change) => {
  const ref = change.after.ref.parent; // reference to the parent
  const now = Date.now();
  const cutoff = now - CUT_OFF_TIME;
  const oldItemsQuery = ref.orderByChild('timeStamp').endAt(cutoff);
  const snapshot = await oldItemsQuery.once('value');
  // create a map with all children that need to be removed
  const updates = {};
  snapshot.forEach(child => {
    updates[child.key] = null;
  });
  // execute all updates in one go and return the result to end the function
  return ref.update(updates);
});
{
  "app_title" : "app",
  "database" : {
    "-Lm3gJ16yk5ZNdt8z2PJ" : {
      "message" : "ok",
      "timeStamp" : "1565594302830",
      "userModel" : {
        "email" : "[email protected]",
        "name" : "Microsoft",
        "photo" : "https://graph.facebook.com/"
      }
    }
  }
}

I have searched for this solution many times but not getting it from anywhere. can anyone please help me.

Upvotes: 0

Views: 337

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599341

Your timestamp is stored as a string, while the code assumes it's a number. I highly recommend fixing the code that writes the timestamp, so that it is stored as a number.

But in the meantime, you can query for a string with:

const oldItemsQuery = ref.orderByChild('timeStamp').endAt(""+cutoff);

Upvotes: 1

Related Questions