Home > OS >  Update Firebase Firestore Data After A Certain Amount of Time
Update Firebase Firestore Data After A Certain Amount of Time

Time:02-25

I want to update a field of my firestore insert after a specific amount of time after it was created. I searched for several possibilities and came up with cloud functions. Unfortunately, java script isn't as easy for me to understand in order to write that function. In addition I red, there isn't a possibility to execute code after a amount of time, anyway.

So how can I handle that problem without writing a lot of js code and paying for the use of that function. Maybe a second application which is just a periodic timer and checks the DateTime field again and again. (Would be possible for me to run that application 24/7)

Thanks guys

CodePudding user response:

You can create a cloud function which triggers when a document is created. You can use timers like setTimeout() to execute a function which changes the document.

Look at the sample code below:

function updateDoc(id) {
    admin.firestore()
    .collection('Orders')
    .doc(id)
    .update({status: 2})
    .then(() => {
        console.log("Document ID: " id " successfully updated!");
    })
    .catch((error) => {
        console.error("Error updating document: ", error);
    });
}

exports.updateField = functions.firestore
    .document('/Orders/{id}')
    .onCreate((snapshot, context) => {
        console.log(context.params.id);
        const id = context.params.id;
        setTimeout(() => updateDoc(id), 600000);
    });

Here's the logs when I executed the function above. Firebase Function Logs

You may want to check Cloud Firestore triggers for other triggers and setTimeout() for other timeout options that you can use in your use-case.

  • Related