allenhinson214
allenhinson214

Reputation: 165

How to get document key in Firestore

I am trying to migrate my existing Firebase realtime database over to firestore and update api calls in my mobile application. I am newer to Firestore and need some guidance. I am trying to fetch users in my database with this function:

        Firestore.firestore().collection("users").getDocuments { snapshot, _ in
            guard let documents = snapshot?.documents else { return }
            users = documents.map({ UserCollection(dictionary: $0.data()) })
        }

I am wanting to get the UID for the user, with realtime database I would always create a let value like this:

guard let uid = snapshot.key else { return }

I know firestore is different but I am not to sure how I can get the UID for my user with the new firestore collection methods. This is an example of how my Firestore collections looks like for users. Its set up like users -> UID -> user's information. Firestore Any recommendation on how I can get the UID for a user?

Upvotes: 0

Views: 1286

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598916

To get the document ID, use the documentID property of the DocumentSnapshot as shown in the documentation on reading multiple documents:

db.collection("cities").whereField("capital", isEqualTo: true)
    .getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                print("\(document.documentID) => \(document.data())")
            }
        }
}

Upvotes: 1

Related Questions