Medo Almouhtadi
Medo Almouhtadi

Reputation: 100

Deleting old data in Realtime database using cloud functions

I have been struggling for a very long time to achieve deleting old data in the realtime database using cloud functions. What am I doing wrong?

I want to delete data that's older than 2 hours every 60 minutes.

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

admin.initializeApp();

'use strict';

const CUT_OFF_TIME = 2 * 60 * 60 * 1000; // 2 Hours in milliseconds.


exports.deleteOldItems = functions.pubsub.schedule('every 60 minutes').onRun(async context => {
  admin.database().ref('/').once('value', async (data) => {
      var ref = data.val();
      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;

      });
      return ref.update(updates);

  });

});

Upvotes: 0

Views: 61

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83093

I didn't check your code for the query based on the cutoff, but we can already see that

var ref = data.val();
//...
const oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff);
//...
return ref.update(updates);

cannot work because data.val() is not a Reference.

You should adapt your code as follows (untested):

exports.deleteOldItems = functions.pubsub.schedule('every 60 minutes').onRun(async (context) => {
    const ref = admin.database().ref();
    
    const now = Date.now();
    const cutoff = now - CUT_OFF_TIME;
    const oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff);
    const snapshot = await oldItemsQuery.get();

    // create a map with all children that need to be removed
    const updates = {};
    snapshot.forEach(child => {
        updates[child.key] = null;

    });
    return ref.update(updates);

});

Upvotes: 1

Related Questions