SLendeR
SLendeR

Reputation: 947

How to access the values of the fields in a Firestore Subcollection

My database looks like this:

Picture

How can I access the values of the fields shown in the "Green area" when I don't have the Collection name of the "Red area"?

Upvotes: 0

Views: 1567

Answers (2)

Renaud Tarnec
Renaud Tarnec

Reputation: 83113

As presented in the documentation, there is no way to list the subcollection of a document with the Client SDKs (Android, iOS, Web).

On the other hand, "the getCollections() method of the Cloud Firestore server client libraries lists all subcollections of a document reference".

Since it seems you are using the Android SDK, you need to find a work around. One possible workaround is to save the sub-collection names in a dedicated a field in the parent document. For example you could use an Array field for storing all the names of the subcollection.

You would normally populate this field when you create the first document of a subcollection, using the Android SDK.

In case, for any reason, you cannot do that from the client, you could use a Cloud Function, which relies on the Admin SDK and therefore can use the getCollections() method referred to above.

Upvotes: 1

Ashish
Ashish

Reputation: 6919

You can not retrieve document value without collection. So i suggest change the Collection name to Friendship status. Then you can easily retrieve fields of documents.

It needs to be like this :

FriendShip

---->Current User id

     --->Friendship Status

         -----> Document id

Then you can use orderby or Equalto Function.

Code for above structure.

mfirebaseFirestore.collection("Friendship").document(mCurrentUser).collection("FriendshipStatus")
                .whereEqualTo("RequestStatus", "Completed")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                Log.d("abc", document.getId() + " => " + document.getData());
                            }
                        } else {
                            Log.d("abc", "Error getting documents: ", task.getException());
                        }
                    }
                });

Note :

Whereequalto is worked when you trying to find data in collection. So you have to query till collection. Then use whereequalto to documents similar to your query

Upvotes: 1

Related Questions