Stack Exchange
Firestore Transaction runs twice, even though first try was successfull
In a cloud function I need to perform a Firestore Transaction, but I just cannot get it to work. The following code is a simplified version, but it still runs into the same problem. doc1 and doc2 are provided by the request.
try {
  const ref1 = db.collection("col1").doc(doc1);
  const ref2 = db.collection("col2").doc(doc2);

  console.log("before");
  await db.runTransaction(async (t) => {
    const data1 = (await t.get(ref1)).data();

    console.log(data1["key"] !== doc2);
    if(data1["key"] !== doc2) {
      throw "Error";
    }

    const data2 = (await t.get(ref2)).data();

    t.update(ref1, {
      key: FieldValue.delete(),
    });
    t.delete(ref2);
  });

  res.status(200).send();
} catch(e) {
  res.status(500).send(e);
}

I know that data["key"] !== doc2 is not true at first. So the "Error" should not get thrown (that is what I would expect). But when I call this function, it seems to call the transaction twice. In the second run the "Error" gets thrown, because the data["key"] gets deleted.
The console output:
before
false
true

