Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the field value in Firebase Firestore automatically after a certain time

My database structure is something like this:

"users": {
"PXZwwGvu0lNwJeov8CMMrETnzVx1": {
      "name": "Ada Lovelace",
      "timestamp" : July 4, 2018 at 4:31:27 PM UTC+5:45
      "happy": true,
    }

"PXZwwGvu0lNwJeov8CMMrETnzVx2": {
      "name": "Charles Babbage",
      "timestamp" : July 5, 2018 at 5:29:15 PM UTC+5:45
      "happy": true,
    }
"PXZwwGvu0lNwJeov8CMMrETnzVx3": {
      "name": "Elon Musk",
      "timestamp" : July 7, 2018 at 9:21:37 PM UTC+5:45
      "happy": true,
    }
}

Here the "timestamp" denotes the time of creation of the document.I want to change the value of field "happy" from true to false exactly one day after the creation of document.The user may close the app after the document creation but the field value should still be changed. Is there any way to do so?

like image 913
bimsina Avatar asked Oct 19 '25 07:10

bimsina


1 Answers

I'd probably set up a Cloud Function for this. This is a piece of code that runs on Google's infrastructure and can interact with Firebase (and other cloud) resources.

If you schedule a Cloud Function to run every hour, you can run a database query that finds all users with a timestamp between 23 and 24 hours ago, and update those.

In pseudo-code this would look something like this:

var now = Date.now();
var 24hoursago = now - ...;
var 23hoursago = now - ...;
var ref = firebase.database().ref("users");
var query = ref.orderByChild("timestamp").startAt(24hoursago).end(23hoursago);
query.once("value").then(function(snapshot) {
  snapshot.forEach(function(user) {
    user.ref.update({ happy: false });
  });
});
like image 200
Frank van Puffelen Avatar answered Oct 20 '25 22:10

Frank van Puffelen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!