Firebase:在与 Firestore 的交易中使用转换器

Firebase: Use converter in transaction with Firestore

我正在尝试在事务中使用 Firestore 数据转换器,在该事务中我将记录添加到集合 (entries) 并更新另一个集合 (users) 中的计数器。但是,我不知道如何在事务中使用转换器,也找不到任何示例。虽然 Firebase 文档通常非常出色,但它们在事务方面似乎有些不足。

// Add new entry and increment user entry counter
async addEntry(entry: Entry): Promise<void> {
    const entryRef = db.collection("entries").doc(entry.id);
    const userRef = db.collection("user").doc(entry.userId);

    await db.runTransaction(async (transaction) => {
      // NOTE: Cannot use converter with transaction???
      await transaction.set(entryRef, entry).withConverter(entryConverter);

      // QUESTION: Is this a proper use of "increment" (ie. inside a transaction)?
      await transaction.update(userRef, { entries: FieldValue.increment(1) });
    });
}

这是没有交易和使用转换器的情况(但我需要交易)。

await db.collection("entries")
  .doc(entry.id)
  .withConverter(entryConverter)
  .set(entry);
await db.collection("users")
  .doc(entry.userId)
  .update({ entries: FieldValue.increment(1) });

如何在事务中安全地执行这两个操作同时使用新数据的转换器?

确实这没有记录,但您可以在事务外部和指定文档之前设置转换器,因为转换器正在应用于集合,它应该可以工作。所以像:

async addEntry(entry: Entry): Promise<void> {
    const entryRef = db.collection("entries").withConverter(entryConverter).doc(entry.id);
    const userRef = db.collection("user").doc(entry.userId);

    await db.runTransaction(async (transaction) => {
      await transaction.set(entryRef, entry);
      await transaction.update(userRef, { entries: FieldValue.increment(1) });
    });
}