2

This is a two in one question.

Part 1: I am storing data in Firestore, and one of my fields is an 'end_date' timestamp field. How can I write a cloud function, so that when this field is over a month in the past, the record is deleted?

Part 2: How can I get this to run every day?

TomH
  • 2,581
  • 1
  • 15
  • 30

1 Answers1

3

You can solve this problem, and related problems, relatively easy by combining the following technologies:

Nodejs, firebase-admin SDK, and the async/await pattern. This is not a full solution, but just to give you an idea:

A firestore query, to get all the documents where 'end_date' is in the past. Something like this (in Nodejs).

let now = new Date(); // Maybe use luxon or moment
now.setMonth(d.getMonth() - 1);
const query = firestore.collection('items')
  .where('end_date', '<=', now)
const snapshots = await query.get();
// Snapshots now contains the documents to delete

A firestore batch, use this to create batch operations, for example to delete. You can do up to 500 operations in a batch:

const batch = firestore.batch();
snapshots.forEach(v => batch.delete(v.ref));
await batch.commit();

Now you just need a way to run this one time per day. Well, after creating an HTTPS firebase function, you can use something like this great free cron-job service cron-job.org, to call your function every day.

Remember that if you use cron-job.org to schedule your job, think about authentication.

Let me know if you need any other help.

DauleDK
  • 3,313
  • 11
  • 55
  • 98