类型为"查询"的值没有成员"getDocument"



我知道这个问题在互联网上有一些答案,但我不明白。这是我运行以下代码时得到的错误代码:

类型为"Query"的值没有成员"getDocument">

let docRef = myDataBase.collection("LogIn Codes").whereField("Code", isEqualTo: code)
docRef.getDocument { (document, error) in
let result = Result {
try document?.data(as: KlassenCodes.self)
}
switch result {
case .success(let KlassenCodes):
if let KlassenCodes = KlassenCodes {
KlassenCodes.id = document!.documentID // Get the ID of the Document as we might need it later
codeArray.append(KlassenCodes) // Save the document into your array
} else {
// A nil value was successfully initialized from the DocumentSnapshot,
// or the DocumentSnapshot was nil.
print("Document does not exist")
}
case .failure(let error):
// A `MyObject` value could not be initialized from the DocumentSnapshot.
print("Error decoding city: (error)")
}
}

我不明白我在哪里犯了错误。

需要

docRef.getDocuments { (querySnapshot, error) in }

请参见此处:https://firebase.google.com/docs/firestore/query-data/queries#execute_a_query

您正在Query对象上使用方法getDocument,该对象没有此方法。

我认为这一定是误解。根据要分配给它的变量名docRefDocumentReference对象(引用)推测,该方法将起作用。然而,在所提出的代码样本中,docRef是返回Query(参考)的whereField方法的结果。即使Query结果只有一个文档,您也必须使用适当的方法。

因此,有两种方法可以纠正这种情况:

  1. 您需要使用getDocuments并重写内部的整个函数来循环遍历文档列表(正如我目前看到的,该函数适用于DocumentReference)。

  2. 将分配更改为类似的内容:let docRef = myDataBase.collection("LogIn Codes").document(<document id>)(参考)它给了你DocumentReference对象,但你使用了确切的id。这可能是个问题,因为我可以看到你稍后会在代码中获得id。

无论如何,问题是在Query对象上使用来自DocumentReference的方法。

最新更新