我有一个集合用户,每个用户都有文档和子集合记录。如何获取所有记录子集合的列表,然后将其合并到一个全局集合中?如何做到这一点?
我有监听器从一个子集合中获取文档:
func recordsObserve(records: [MRecords], completion: @escaping (Result<[MRecords], Error>) -> Void) -> ListenerRegistration? {
var records = records
let recordsRef = db.collection(["users", currentUserId, "records"].joined(separator: "/"))
let recordsListener = recordsRef.addSnapshotListener { (querySnapshot, error) in
guard let snapshot = querySnapshot else {
print(1)
completion(.failure(error!))
return
}
snapshot.documentChanges.forEach { (diff) in
guard let record = MRecords(document: diff.document) else { return }
switch diff.type {
case .added:
guard !records.contains(record) else { return }
records.append(record)
case .modified:
guard let index = records.firstIndex(of: record) else { return }
records[index] = record
case .removed:
guard let index = records.firstIndex(of: record) else { return }
records.remove(at: index)
}
}
completion(.success(records))
}
return recordsListener
}
但我需要监听器来获取所有用户的所有记录子集。
答案 0 :(得分:1)
您要查找的内容在 Firestore 中称为 collection group query。要从所有 records
集合中获取所有文档,它看起来像这样:
db.collectionGroup("records").getDocuments { (snapshot, error) in
// ...
}
在遍历快照中的文档时,您可以使用记录的 DocumentReference
和 CollectionReference
的 parent
属性获取用户文档的文档 ID。