I have collection users with documents and subcollections records in each of them. How I can get list of all subcollections of records and then merge it in one global collection? How this can be done?
I've listener to get documents from one subcollection:
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
}
But I need listener to get all subcollections of records from all users.
What you're looking for is known as a collection group query in Firestore. To get all documents from all records
collection, it'd look something like this:
db.collectionGroup("records").getDocuments { (snapshot, error) in
// ...
}
While looping over the documents in the snapshot, you can get the document ID of the user document by using the parent
property of the record's DocumentReference
and CollectionReference
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.