gpt4 book ai didi

swift - 删除文档时如何在 Firestore 事务中处理错误

转载 作者:行者123 更新时间:2023-12-04 09:32:10 27 4
gpt4 key购买 nike

  • 我有一个应用程序,我必须在其中使用 验证用户文档是否仍然存在 在我开始对不同的集合进行一系列批量写入之前,在一个集合中
  • 最好的方法是使用 firestore交易
  • 我能够理解交易的概念并且它在实践中起作用,但我很难理解 会抛出哪些错误 - 所以这是我场景中的一个例子
  • 案例1:我运行事务。 Firestore 首先读取文档,然后进行事务性写入/更新等,然后重新检查文档是否已被修改。在这种情况下,假设另一个用户删除了此文档 - 交易有什么作用?文档说明它将继续重试,但如果文档本身被删除,它会重试吗?
  • 案例2:我运行事务。 Firstore 首先读取文档。它实现了文档本身并不存在。现在会发生什么?

  • 我的问题是,在这两种情况下,哪些错误被称为?我应该明确检查 snapshot.exist 然后分配一个错误指针吗? 我知道这些问题很多,所以总而言之,在文档删除的情况下,事务如何处理错误
    我不能发布我的代码,因为它来自工作,我被禁止这样做。因此,我从 firestore 文档中发布代码。在下面的情况下会发生什么
  • 事务开始时SF文件不存在
  • SF 文档在开始时存在,但在事务结束之前被另一个用户删除。谷歌再次声明它会继续尝试,但为什么它会在文档本身被删除时重试
  • let sfReference = db.collection("cities").document("SF")

    db.runTransaction({ (transaction, errorPointer) -> Any? in
    let sfDocument: DocumentSnapshot
    do {
    try sfDocument = transaction.getDocument(sfReference)
    } catch let fetchError as NSError {
    errorPointer?.pointee = fetchError
    return nil
    }

    guard let oldPopulation = sfDocument.data()?["population"] as? Int else {
    let error = NSError(
    domain: "AppErrorDomain",
    code: -1,
    userInfo: [
    NSLocalizedDescriptionKey: "Unable to retrieve population from snapshot \(sfDocument)"
    ]
    )
    errorPointer?.pointee = error
    return nil
    }

    // Note: this could be done without a transaction
    // by updating the population using FieldValue.increment()
    transaction.updateData(["population": oldPopulation + 1], forDocument: sfReference)
    return nil
    }) { (object, error) in
    if let error = error {
    print("Transaction failed: \(error)")
    } else {
    print("Transaction successfully committed!")
    }
    }

    最佳答案

    What does the transaction do? Documentation states it will keep retrying but would it retry if the document itself is deleted?


    是的。

    I run transaction. Firstore first reads document. It realizes the document itself does not exist. What happens now?


    可以处理不存在的文件。您的事务处理程序必须对此进行检查,然后决定在这种情况下该怎么做。

    关于swift - 删除文档时如何在 Firestore 事务中处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62784219/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com