简体   繁体   中英

Firestore Cloud Function. transaction vs get() => update()

I have a document containing a field which is an array of integers, this document is created once a day, 7 days a week via a onCreate() trigger. I need to count the occurrences of each item in the array. In other app I did it with a get() then set() (or update() for that matter). I will run a for loop in the array and add all the promises to a promises array and at the end: Promise.all{promisesArray} .

Just found out about transactions and it is working ok for my very basic javascript.

My question is which one should I use, what is the benefit to use a transaction in my case, if any? The document is created by an admin and not an end user, is not that it will be created by million users.

Below is the code I use to count the occurrences:

// Ref.get() then Ref.update()
promisesArray.push(docRef.get()
    .then(doc => {
        return docRef.update('count', doc.data().count + 1);
    })).catch(error => {
    console.log("Error" + error);
});

// Using a Transaction
promisesArray.push(firestore.runTransaction(transaction => {
    return transaction.get(docRef)
        .then(doc => {
            return transaction.update(docRef, {
                count: doc.data().count + 1
            });
        });
}).catch(error => {
    console.log("Error" + error);
}));

If you know that a document may only be written by only one program at any time, you don't need a transaction. The purpose of a transaction is to handle a situation where multiple users/programs may all be trying to write a document at the same time. Or, you need to atomically update a bunch of documents in a single write operation, for consistency between all the documents.

If you are only writing a single document in a Cloud Function during onCreate, then you probably don't need a transaction. If you need several documents to appear all at the exact same moment in time, as a result of some common computations, then you probably do need a transaction.

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