【问题标题】:Flutter: Exit a Firestore transaction if conditions not metFlutter:如果条件不满足,则退出 Firestore 事务
【发布时间】:2020-01-23 10:52:12
【问题描述】:

在以下 Firestore 事务中,如果条件 (someNumber

例外情况:

PlatformException(PlatformException(9, Transaction failed all retries.: 在事务中读取的每个文档也必须写入该事务中。, null))

交易:

_myFunction({@required docId,}) {
  try {
  final DocumentReference docRef = Firestore.instance.collection('collection').document(docId);
  Firestore.instance.runTransaction(
    (tx) async { 
      DocumentSnapshot snapshot = await tx.get(docRef);
      var someNumber = snapshot['someNumber'] ?? 0;
        if (snapshot.exists && someNumber < 2) {
          await tx.update(
            docRef,
              {
              'someNumber': FieldValue.increment(1),
              },
            );
        } else {
          print("someNumber exceeded");
          return;
        }
      },
    );
  } catch (e) {
    print(e);
  }
}

如果 someNumber 小于 2,则事务正常工作。需要在事务内部读取此变量,因为两个用户可能同时更新该值。

【问题讨论】:

    标签: flutter google-cloud-firestore


    【解决方案1】:

    我也遇到过这个错误。根据this discussion,这似乎是一个已知的限制(尽管这个讨论大约在 2 年前开始,但似乎没有任何改变):

    不幸的是,目前这是客户端 SDK 中的一个已知限制(希望在 GA 之前得到解决)。客户端对事务使用乐观并发(没有锁定,而是客户端说,“作为我写入的先决条件,确保文档版本仍然是 X”,其中 X 是客户端在事务期间读取的任何版本)。目前,客户无法说“还要确保我没有编写的其他文档仍然是版本 Y。”我们将添加此功能并更改客户端 SDK 以允许在不修改文档的情况下阅读文档,但我没有明确的时间表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-21
      • 1970-01-01
      • 2021-05-15
      • 1970-01-01
      相关资源
      最近更新 更多