简体   繁体   中英

Update Firebase Firestore Data After A Certain Amount of Time

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

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 函数日志

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM