0

I am having issues where firebase is not updating the stock values in my database correctly on some occasions. I am using FieldValue.increment() and it works most of the time, but doesn't update maybe 1% of the time for some reason, even though there was no error message from firebase. I was looking at the firebase documentation and it seems that I need to make my writes to the database idempotent in the case of retries or fails. I was thinking about using transactions to check the database if a change has occurred before updating, but my code is currently writing to multiple collections using batch writes.

I was wondering if it is possible to return a batch write commit from a transaction in Firebase? I know you can do the writes inside of the transaction, but would there by any issues if you created a batch and then, based on your read operation for the transaction, you either commit or don't commit the batch of writes? It seems to be working ok when I run the program, but I'm worried there may be potential edge cases I'm not seeing. Here is an example of what I am talking about...

  const batch = db.batch();
  const ref1 = db.collection('references').doc('referenceId1');
  const ref2 = db.collection('references').doc('referenceId2');
  batch.update(ref1, {completed: true});
  batch.set(ref2, ...)
  return db.runTransaction((transaction)=> {
    return transaction.get(ref1).then((doc) => {
      const document = doc.data();
      if(!ref1.completed){
        return batch.commit()
      }
   })
  })
  .then(function() {
    console.log("Transaction successfully committed!");
  }).catch(function(error) {
    console.log("Transaction failed: ", error);
  });
  • 1
    It doesn't make sense to commit a batch inside a transaction. Batches and transactions are different operations and should be completely separate from each other. – Doug Stevenson Oct 28 '20 at 22:02
  • Thanks for your reply, Doug. Ok then. Would you suggest returning all the database calls in the transaction, then? I'm just trying to find a solution to the stock value not updating correctly. I'm submitting as a batch write right now where i update user data with a complete tag and change the inventory accordingly, so i thought all writes would just fail if the stock update didn't complete correctly. But, the other writes in the batch seem to be completing, while the increment is not happening on the stock value. It's rare, but I need it to be 100%. – Bashir Egeh Oct 28 '20 at 22:37

0 Answers0