swift - Swift 5 Firestore:检查数据库中是否存在集合
问题描述
我正在尝试检查我的 Firestore 数据库中是否存在某个集合,这是我的代码:
let db = Firestore.firestore()
db.collection(pickedClass).getDocuments { (snapshot, error) in
if error == nil && snapshot != nil {
if snapshot!.documents.count > 0 {
for document in snapshot!.documents {
let documentData = document.data()
let info = documentData["info"] as! [String: Any]
output.append(object)
}
self.performSegue(withIdentifier: "showTutors", sender: output)
} else {
self.createAlert(title: "No Tutors Found", message: "Sorry, there are no tutors for this class", buttonMsg: "Okay")
}
}
}
我从运行中得到的异常显然来自第二行db.collection(pickedClass).getDocuments
,如下所示:
*** Terminating app due to uncaught exception 'FIRInvalidArgumentException', reason: 'Invalid collection reference. Collection references must have an odd number of segments, but has 0'
terminating with uncaught exception of type NSException
奇怪的是,大多数时候这不是问题,当集合不存在时用户会看到警报,但有时会发生这种情况。直到今天我才遇到这个问题,我已经运行这个数据库和这段代码两个多月了。
非常感谢任何帮助!
解决方案
嗨,我在学习时第一次实施 FireStore,我发现这个答案你可以使用下面提到的代码。
Firestore.firestore().collection("YOUR_COLLECTION_NAME_HERE") .document("INSIDE_YOUR_COLLECTION_USE_DOCUMENT_ID_HERE_WHICH_YOU_WANT_TO_CHECK") .getDocument { (document, error) in debugPrint(document?.exists) if document?.exists ?? false { // EXIST } else { // NOT-EXIST } }