0

I've been trying to get this firestore transaction to run but it always throws the same error. I've tried adding a return in the txn.get an txn.set and txn.update, yet it never works.

Here's the transaction I'm trying to get to work:

return db.runTransaction((txn) => {
  // - - - Update inventory - - -
  Products.forEach((product) => {
    // Get existing product (if it exists)
    const docref = db
      .collection("Inventory")
      .doc(product.Description + product.Batch);
    return txn.get(docref).then((doc) => {
      if (doc.exists) {
        // Update values
        const previous_amount = Number(doc.data().Cantidad);
        const new_amount = 0;
        if (MovementType == "Entrada") {
          new_amount = previous_amount + product.Quantity;
        } else {
          new_amount = previous_amount - product.Quantity;
        }
        txn.update(docref, { Cantidad: new_amount });
      } else if (MovementType == "Entrada") {
        // Create document
        txn.set(docref, {
          Articulo: product.Description,
          Cantidad: Number(product.Quantity),
          Precio: product.Subtotal,
          Lote: product.Batch,
          FechaDeIngreso: new Date().toISOString(),
          FechaDeCaducidad: product.ExpiryDate,
        });
      }
    });
  });

  // - - - Register Movement - - -
  const movementDocRef = db.collection("Movimientos").doc();
  txn.set(movementDocRef, {
    MovementType: MovementType,
    Person: Person,
    Products: Products,
    Date: new Date().toISOString(),
    Cfdi: Cfdi != null ? Cfdi.Id : null,
  });
});
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Where is your code executed? In a front-end (via the JS SDK) or in a Node.js backend or a Cloud Function (via the Admin SDK)? – Renaud Tarnec May 28 '22 at 17:37
  • In front-end (in a vue application) – Santy Arellano May 28 '22 at 17:40
  • The error message is telling you that you didn't return a promise as required. All those get() operations need to factor into a final promise that indicates when your transaction is complete. If you do a web search for that error message you'll learn more. You will need to handle all promises generated through your transaction just like you would any other series of promises. Be sure to use the API documentation to learn which methods do return promises. – Doug Stevenson May 28 '22 at 17:51

0 Answers0