【问题标题】:Firestore how stop Transaction?Firestore如何停止Transaction?
【发布时间】:2018-11-17 00:32:14
【问题描述】:

在事务中我只想在数据不存在时写入数据

DocumentReference callConnectionRef1 = firestore.collection("connectedCalls").document(callChannelModel.getUid());

  firestore.runTransaction(new Transaction.Function < Void > () {
 @Override
 public Void apply(Transaction transaction) throws FirebaseFirestoreException {
  DocumentSnapshot snapshot = transaction.get(callConnectionRef1);

   Log.d(TAG, callChannelModel.getUid());


  if (!snapshot.exists()) {
   //my code
   transaction.set(callConnectionRef1, model);
  } else {
   //do nothing   
  }
  return null;

 });

您可以在我的文档中看到基于 uid 的引用,在我的日志中我正在打印 uid

所以,如果 uid 的数据不存在,我的日志只打印一次,我在其他地方调用 transaction.set(),它会一直显示数据已经存在的 uid 日志,如果我不调用 transaction.set( )

我怎样才能阻止它。

【问题讨论】:

  • 您能否详细说明“继续运行”的含义? runTransaction 根本不回来吗?
  • 我添加了事务开始的日志......它一直显示该日志
  • 请问您能否在问题中提供更多详细信息?目前我不清楚你的意思。如果您能提供minimal reproducible example,那将非常有帮助。
  • 我编辑了我的问题...请看一下
  • 我的猜测是一个异常单独发生。同样,如果您可以将您的问题编辑为minimal reproducible example,这将使某人更容易重现该问题,那将非常有帮助。 (示例应该什么都不做演示问题。)

标签: javascript firebase google-cloud-firestore


【解决方案1】:

文档中给出了一个例子,只要抛出一个异常就会退出事务并停止执行。


db.runTransaction(new Transaction.Function<Double>() {
    @Override
    public Double apply(Transaction transaction) throws FirebaseFirestoreException {
        DocumentSnapshot snapshot = transaction.get(sfDocRef);
        double newPopulation = snapshot.getDouble("population") + 1;
        if (newPopulation <= 1000000) {
            transaction.update(sfDocRef, "population", newPopulation);
            return newPopulation;
        } else {
            throw new FirebaseFirestoreException("Population too high",
                    FirebaseFirestoreException.Code.ABORTED);
        }
    }
}).addOnSuccessListener(new OnSuccessListener<Double>() {
    @Override
    public void onSuccess(Double result) {
        Log.d(TAG, "Transaction success: " + result);
    }
})
.addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        Log.w(TAG, "Transaction failure.", e);
    }
});
DocSnippets.java

【讨论】:

  • 这个例子不起作用,因为事务在 Android 上尝试了 5 次。
【解决方案2】:

在 Android 上我也遇到过这种情况。事务执行 5 次尝试应用自身,然后才调用 onFailure() 函数(即使您在 apply() 函数中抛出异常)。

但看起来这是预期的行为:

  1. 请看这里:https://googleapis.dev/python/firestore/latest/transaction.html
    注意 MAX_ATTEMPTS 默认为 5。
  2. 在这个 github 问题 https://github.com/firebase/firebase-js-sdk/issues/520 中有一个添加“重试次数”选项的请求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 2012-12-23
    • 2019-05-25
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    相关资源
    最近更新 更多