Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a specific field from Cloud FireStore Firebase in Swift

Here is my data structure:

data structure

I have an ios app that is attempting to access data from Cloud Firestore. I have been successful in retrieving full documents and querying for documents. However I need to access specific fields from specific documents. How would I make a call that retrieves me just the value of one field from Firestore in swift? Any Help would be appreciated.

like image 953
Kunwar Sahni Avatar asked Jan 18 '18 01:01

Kunwar Sahni


3 Answers

There is no API that fetches just a single field from a document with any of the web or mobile client SDKs. Entire documents are always fetched when you use getDocument(). This implies that there is also no way to use security rules to protect a single field in a document differently than the others.

If you are trying to minimize the amount of data that comes across the wire, you can put that lone field in its own document in a subcollection of the main doc, and you can request that one document individually.

See also this thread of discussion.

It is possible with server SDKs using methods like select(), but you would obviously need to be writing code on a backend and calling that from your client app.

like image 139
Doug Stevenson Avatar answered Sep 22 '22 18:09

Doug Stevenson


This is actually quite simple and very much achievable using the built in firebase api.

        let docRef = db.collection("users").document(name)

        docRef.getDocument(source: .cache) { (document, error) in
            if let document = document {
                let property = document.get(field)
            } else {
                print("Document does not exist in cache")
            }
        }
like image 27
Anthony Sobo Avatar answered Sep 22 '22 18:09

Anthony Sobo


There is actually a way, use this sample code provided by Firebase itself

let docRef = db.collection("cities").document("SF")

docRef.getDocument { (document, error) in
    if let document = document, document.exists {
        let property = document.get('fieldname')
        print("Document data: \(dataDescription)")
    } else {
        print("Document does not exist")
    }
}
like image 22
Yash Kothari Avatar answered Sep 21 '22 18:09

Yash Kothari