简体   繁体   English

阅读 firebase 集合中的文档

[英]Read document in firebase collection

I have a firestore function which adds data to a collection:我有一个 Firestore function 它将数据添加到集合中:

func blockUser(userId: String) {
    Firestore.firestore().collection("blocked").document(Auth.auth().currentUser!.uid).collection("userBlocked").document(userId).setData([:])
}

Works fine, creates a structure like (as expected):工作正常,创建一个结构,如(如预期):

在此处输入图像描述

and in the userBlocked collection its adds a user id which has been blocked like so:并在 userBlocked 集合中添加一个已被阻止的用户 ID,如下所示:

在此处输入图像描述

Im trying to retrieve the userBlocked with the following:我正在尝试使用以下内容检索 userBlocked:

    Firestore.firestore().collection("blocked").document(Auth.auth().currentUser!.uid).collection("userBlocked").getDocuments{(snapshot,error) in
        guard let snap = snapshot else {
            print("error getting blocked users")
            return
        }
        //var blockedUsers = [User]()
        for document in snap.documents {
            let dict = document
            print("printing blocked user - \(dict)")
        }
    }

In the logs im getting:在我得到的日志中:

printing blocked user - <FIRQueryDocumentSnapshot: 0x6000015c3610>

Im trying to retrieve each blocked user?我试图检索每个被阻止的用户? but can't seem to get each user id, it should be getting back d8j5fU8rinUcAEZyNZ5qAIzoa1j2但似乎无法获取每个用户 ID,它应该返回d8j5fU8rinUcAEZyNZ5qAIzoa1j2

You're going to have to write code to get the document data out of the QuerySnapshot that was delivered to your callback.您将不得不编写代码以从传递给回调的QuerySnapshot中获取文档数据。 I suggest starting with the documentation .我建议从文档开始。

In your code, snap is a QuerySnapshot , and document is a QueryDocumentSnapshot .在您的代码中, snapQuerySnapshot ,而documentQueryDocumentSnapshot You can see from the linked API docs that QueryDocumentSnapshot has a data() method that gets you the document data as a dictionary.您可以从链接的 API 文档中看到 QueryDocumentSnapshot 有一个data()方法,可以将文档数据作为字典获取。

However, you didn't write any fields to the document, so the dictionary will be empty.但是,您没有在文档中写入任何字段,因此字典将为空。 If you want the ID of the document, you can use document.documentID .如果您想要文档的 ID,可以使用document.documentID

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM