【发布时间】: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