【问题标题】:Firestore use reference type with where clauseFirestore 使用带有 where 子句的引用类型
【发布时间】:2019-06-13 14:31:55
【问题描述】:

我正在尝试使用引用类型向 Firestore 写入查询。我已经检查了关于 SO 的文档和一些问题,但没有理解如何在 where 条件下使用引用。 我确实不明白引用字段可以帮助我获取它引用的文档,因为引用是一条路径。我有一对一的结构,并希望通过它在“相反”方向上的引用来获取文件。同时,我还有其他具有一对多结构的表。我想对他们使用相同的方法。

这是我的结构。这是一对一的。 activeSessions 集合中的一个文档在表集合中必须只有一个相应的文档:

Root collection
    |
    |
    -- tables (collection)
    |   |
    |   |
    |   -- tableName
    |   |
    |   -- tableCapacity
    |
    |
    -- activeSessions (collection)
        |
        |
        -- openTime
        |
        -- tableReference (reference that contains path to one of tables document.)

所以我想从 activeSessions 集合中获取文档,该集合引用了我已经拥有的文档。 我尝试了以下函数,但它返回任何表格文档的文档。

class func getActiveSession (forTable table: TablesTable, completion: @escaping (TableSessionTable?, Error?) -> Void) {
    // table.firebaseID contains unique id of the table document.
    // let userData = appDelegate.db.collection("usersData").document(userId)
    let tableReference = userData.collection("tables").document(table.firebaseID!)
    print(table.firebaseID)
    print (tableReference)
    let tableSessionCollection = userData.collection("activeSessions")
    tableSessionCollection.whereField("tableReference", isEqualTo: tableReference)
    tableSessionCollection.addSnapshotListener { (snapshot, error) in
        if let error = error {
            completion(nil, error)
            return
        }

        if let snapshot = snapshot {

            let ref = data["tableReference"] as! DocumentReference
            print("tablesession reference is to \(ref.documentID)")
            print(ref)
            completion(tableSession, error)
        }
    }
}

根据this 的问题,一切都应该可以正常工作。但事实并非如此。 我已将一些打印件放入我的函数中,并且根据输出,它从 tableSession 查询中返回一个文档两次。它是对同一个 documentID 的引用。但同时 DocumentReference 对象的实例不同:

Optional("12tVcpi93aPbN8qWmtLx")
<FIRDocumentReference: 0x6000011e76e0>
Optional("s7FCXMlCdx61OmtHyQvy")
<FIRDocumentReference: 0x6000011e5b60>

tablesession reference is to s7FCXMlCdx61OmtHyQvy
<FIRDocumentReference: 0x6000011e3600>

tablesession reference is to s7FCXMlCdx61OmtHyQvy
<FIRDocumentReference: 0x60000119b4c0>

【问题讨论】:

    标签: ios swift google-cloud-firestore


    【解决方案1】:

    这与您查询引用类型字段这一事实没有任何关系。问题是您没有正确构建查询。您需要将过滤器链接在一起。每个添加的过滤器都会返回一个新的查询对象,您需要在该新查询的基础上进行构建。

    let tableReference = userData.collection("tables").document(table.firebaseID!)
    let tableSessionCollection = userData
        .collection("activeSessions")
        .whereField("tableReference", isEqualTo: tableReference)
    tableSessionCollection.addSnapshotListener { (snapshot, error) in
        // ...
    }
    

    另请参阅:Firestore: Multiple conditional where clauses

    【讨论】:

      猜你喜欢
      • 2021-12-25
      • 2019-05-29
      • 1970-01-01
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 2020-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多