Gurmukh Singh
Gurmukh Singh

Reputation: 2017

Read document in firebase collection

I have a firestore function which adds data to a collection:

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):

enter image description here

and in the userBlocked collection its adds a user id which has been blocked like so:

enter image description here

Im trying to retrieve the userBlocked with the following:

    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

Upvotes: 0

Views: 91

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

You're going to have to write code to get the document data out of the QuerySnapshot that was delivered to your callback. I suggest starting with the documentation.

In your code, snap is a QuerySnapshot, and document is a QueryDocumentSnapshot. You can see from the linked API docs that QueryDocumentSnapshot has a data() method that gets you the document data as a dictionary.

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.

Upvotes: 1

Related Questions