【问题标题】:Why does Firestore codable support not work for this example为什么 Firestore 可编码支持不适用于此示例
【发布时间】:2022-01-08 11:04:19
【问题描述】:

在第一个示例中,它编译并正常工作,返回所有项目文档。

public struct Project: Codable, Identifiable, Equatable {
        
    @DocumentID public var id : String? = UUID().uuidString
    public var name: String
    public var password: String

}
    public static func testQuery() async ->  [Project] {
        let db = Firestore.firestore()
        let ref = db.collection("Project")
        let snapshot = try? await ref.getDocuments()
        if let snapshot = snapshot {
            return snapshot.documents.compactMap { document in
                return try? document.data(as: Project.self)
            }
        } else {
            return [Project]()
        }
    }

但是,如果我将 ref 更改为声明为 Query,则文档不再支持可编码。我该如何解决这个问题,因为我需要使用 Query 根据传递的参数动态构建查询。

    public static func testQuery() async ->  [Project] {
        let db = Firestore.firestore()
        let ref: Query = db.collection("Project")  // this line changed
        let snapshot = try? await ref.getDocuments()
        if let snapshot = snapshot {
            return snapshot.documents.compactMap { document in
                return try? document.data(as: Project.self). // this no longer compiles
            }
        } else {
            return [Project]()
        }
    }

【问题讨论】:

  • 查询人从何而来?项目?我从来没有听说过。
  • 你检查过这个comprehensive guide吗?
  • 是的,问题在于使用查询。我需要将 ref 声明为 Query 的原因是我需要基于输入以编程方式在 .whereField 构造,而不是在编译时知道它们。查询成功构建并成功返回文档,但是,无论出于何种原因,这些文档都不可解码(似乎应该如此)。也许这是 Firestore Swift 支持中的一个错误
  • let ref: Query = db.collection("Project") 更改为let ref: Query = db.collection("Project").whereField(addSomethingThatYouKnowWillReturnADocument) 会发生什么?那它有用吗?
  • 不幸的是同样的问题

标签: swift firebase google-cloud-firestore


【解决方案1】:

事实证明,如果您将引用从 Query 转换为 CollectionReference,那么您可以使用内置的编码和解码功能。

public static func testQuery() async ->  [Project] {
        let db = Firestore.firestore()
        let ref: Query = db.collection("Project")  // this line changed
        let ref2 = ref as! CollectionReference
        let snapshot = try? await ref2.getDocuments()
        if let snapshot = snapshot {
            return snapshot.documents.compactMap { document in
                return try? document.data(as: Project.self). // this no longer compiles
            }
        } else {
            return [Project]()
        }
    }

【讨论】:

    猜你喜欢
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多