Home > Enterprise >  How can I make some document fields get reset every x hours after the document was added?
How can I make some document fields get reset every x hours after the document was added?

Time:08-05

So I have some firestore with some data, I want it so that every 24 hours after the document was added all the document fields get reset to zero. So like new document gets added? a day later reset all the fields for the document, then tomorrow same time do that again and again the next day. I can't really think of an efficient way to do this though?

I also put the date as a field in the document and someone suggested to call the function every 10 minutes and just query the documents that have a date older than 24 hours but this wouldn't exactly be accurate enough because if the function gets called at 23 hours 59 minutes then it'll only recall the function again and update the document at 24 hours and 9 minutes.

Does anybody know how I can do this in a clean way or is there even such a thing? Should I just do the approach with calling it every 10 minutes and querying documents with a date older than 24 hours?

CodePudding user response:

Good question. Firebase make function calls very cheap, so you can make a lot of requests without it costing you much. I would setup a function to run every x minutes, maybe every 5 minutes, and reset any required documents based on a timestamp stored on the document.

But, this still isnt ideal, maybe you should rethink your business logic, can you structure your application differently to remove the need to do this? For example, can you check when a user makes a request if the fields should be reset before you proceed to your next piece of functional logic?

CodePudding user response:

Does anybody know how I can do this in a clean way or is there even such a thing?

Instead of scheduling a Cloud Function to run every X minutes, one "clean way" is to use Cloud Tasks to invoke an HTTPS Cloud Function at a specific time in the future, as detailed in the following article.

  • Related