简体   繁体   English

输入“QuerySnapshot?” 没有成员“文件”

[英]Type 'QuerySnapshot?' has no member 'documents'

I am trying to get data back from the Firebase Firestore but have come in to one or maybe more problems我正在尝试从 Firebase Firestore 取回数据,但遇到了一个或多个问题

Here is my code这是我的代码

I a trying to get a specific document with the id of the current user id我试图获取具有当前用户 ID 的特定文档

import SwiftUI
import Firebase
import FirebaseFirestore
import FirebaseFirestoreSwift


class UsersModel: ObservableObject {
    
    @Published var userData = [UserData]()
    
    let userID = Auth.auth().currentUser!.uid
    
    private var db = Firestore.firestore()
    
    func fetchData() {
            
            db.collection("users").document(userID).addSnapshotListener { (querySnapshot, error) in
                guard let document = QuerySnapshot?.documents() else {
                    print("No documents")
                    return
                }
                
                self.userData = document.compactMap{(QueryDocumentSnapshot) -> UserData? in
                    return try? QueryDocumentSnapshot.data(as: UserData.self)
                }
            }
        }
}

but on this line guard let document = QuerySnapshot?.documents() else { I get this error Type 'QuerySnapshot?' has no member 'documents'但是在这条线上guard let document = QuerySnapshot?.documents() else {我收到这个错误Type 'QuerySnapshot?' has no member 'documents' Type 'QuerySnapshot?' has no member 'documents'

I am using the Coddle protocol我正在使用 Coddle 协议

Here is my UserData这是我的用户数据

import SwiftUI
import FirebaseFirestoreSwift

struct UserData: Identifiable, Codable {
    @DocumentID var id: String?
    var username: String
    var ImageURl: URL
}

What am I doing wrong and how can I fix this please我做错了什么,请问我该如何解决

Many Thanks for your help非常感谢您的帮助

Your snapshot is already a document so you can't query for 'documents' because it's not a collection您的快照已经是文档,因此您无法查询“文档”,因为它不是集合

All you need to do is get your query snapshot from the listener closure, [querySnapshot] and get it's data like so:您需要做的就是从侦听器闭包 [querySnapshot] 获取查询快照并获取它的数据,如下所示:

func fetchData() {    
    db.collection("users").document(userID).addSnapshotListener { (documentSnapshot, error) in
        guard let document = documentSnapshot?.data() else {
            print("No documents")
            return
        }
        
        self.userData = document.compactMap{(QueryDocumentSnapshot) -> UserData? in
            return try? QueryDocumentSnapshot.data(as: UserData.self)
        }
    }
}

It appears you are attempting to read in a single user's data, which would be a single document.您似乎正在尝试读取单个用户的数据,这将是一个文档。 No reason to addSnapshotListener unless you want to be notified of changes.除非您想收到更改通知,否则没有理由添加 SnapshotListener。

Also, there's no reason to .compactMap because the users data can be directly read from the document.此外,没有理由使用.compactMap ,因为可以直接从文档中读取用户数据。

There are many options for reading a single document and mapping it to an object;读取单个文档并将其映射到 object 有很多选项; here's two:这里有两个:

Here's a simplifed object这是一个简化的 object

struct UserData: Identifiable, Codable {
    @DocumentID var id: String?
    var username: String
    var ImageUrl: String
}

Option 1 to read the user using getDocument { (document, error) and then casting the document to a User object after being read选项 1 使用getDocument { (document, error)读取用户,然后在读取后将文档投射到用户 object

func readUser() {
    let userID = "uid_0"
    let docRef = self.db.collection("users").document(userID)

    docRef.getDocument { (document, error) in
        if let err = error {
            print(err.localizedDescription)
            return
        }

        if let doc = document {
            let user = try! doc.data(as: UserData.self)
            print(user.username, user.ImageUrl)
        }
    }
}

and then the second, super simple (and way cooler) option to map the users data to the user object when it's read in然后是第二个,超级简单(也更酷)选项 map 用户数据读入时为用户 object

func readUser2() {
    let userID = "uid_0"
    let docRef = self.db.collection("users").document(userID)

    docRef.getDocument(as: UserData.self, completion: { result in
        switch result {
        case .success(let user):
            print(user.username, user.ImageUrl)
        case .failure(let error):
            print(error.localizedDescription)
        }
    })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter firestore QuerySnapshot 在 Android 中没有 getter“文档”的实例 - Flutter firestore QuerySnapshot has no instance of getter 'documents' in Android 没有为类型“QuerySnapshot”定义吸气剂“文档”<object?> '</object?> - The getter 'documents' isn't defined for the type 'QuerySnapshot<Object?>' 没有为类型“QuerySnapshot”定义吸气剂“文档” <map<string, dynamic> >' </map<string,> - The getter 'documents' isn't defined for the type 'QuerySnapshot<Map<String, dynamic>>' SwiftUI:“DocumentSnapshot”类型的值? 没有成员“文件” - SwiftUI: Value of type 'DocumentSnapshot?' has no member 'document' 应为“QuerySnapshot”类型的值<object?> ',但得到的是 '_MapStream 类型之一<querysnapshotplatform, querysnapshot<map<string, dynamic> >>'</querysnapshotplatform,></object?> - Expected a value of type 'QuerySnapshot<Object?>', but got one of type '_MapStream<QuerySnapshotPlatform, QuerySnapshot<Map<String, dynamic>>>' 'Future 类型的值<querysnapshot<map<string, dynamic> &gt;&gt;' 不能分配给“QuerySnapshot”类型的变量<object?> ' </object?></querysnapshot<map<string,> - A value of type 'Future<QuerySnapshot<Map<String, dynamic>>>' can't be assigned to a variable of type 'QuerySnapshot<Object?>' 模块“@firebase/firestore”在 Angular 12 中没有导出成员“类型”错误 - Module '"@firebase/firestore"' has no exported member 'type' ERROR in Angular 12 SwiftUI - Firebase:“String”类型的值没有成员“documentID” - SwiftUI - Firebase: Value of type 'String' has no member 'documentID' 为什么 vs 代码说方法 '.getDocuments' 和 getter 文档没有分别为类型 Query 和 QuerySnapshot 定义? - Why is vs code saying the method '.getDocuments' and the getter documents are not defined for types Query and QuerySnapshot respectively? Flutter/Firestore - 错误:“列表”类型的值<string> Function(QuerySnapshot)' 不能分配给 'List' 类型的变量<dynamic> '</dynamic></string> - Flutter/Firestore - Error: A value of type 'List<String> Function(QuerySnapshot)' can't be assigned to a variable of type 'List<dynamic>'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM