Firebase Cloud Functions - Delete Entries where timestamp field is over a month old and run daily

有些话、适合烂在心里 提交于 2021-02-19 05:38:10

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/50804428/firebase-cloud-functions-delete-entries-where-timestamp-field-is-over-a-month

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!