Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore - How Can I Get The Collections From a DocumentSnapshot?

Let's say I have a userSnapshot which I have got using get operation:

DocumentSnapshot userSnapshot=task.getResult().getData();

I know that I'm able to get a field from a documentSnapshot like this (for example):

String userName = userSnapshot.getString("name");

It just helps me with getting the values of the fields, but what if I want to get a collection under this userSnapshot? For example, its friends_list collection which contains documents of friends.

Is this possible?

like image 551
Tal Barda Avatar asked Oct 16 '17 16:10

Tal Barda


People also ask

How do I get all the collections in firestore?

You can do the following: const admin = require("firebase-admin"); const db = admin. firestore(); db. listCollections() .

How do I query a collection in firestore?

To start querying a collection, you need to provide the hooks with a CollectionReference or Query reference created directly from the firebase/firestore library. The reference can be a simple collection pointer or a fully constrained query using the querying functionality provided by the Firestore SDK.


1 Answers

Queries in Cloud Firestore are shallow. This means when you get() a document you do not download any of the data in subcollections.

If you want to get the data in the subcollections, you need to make a second request:

// Get the document
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();

            // ...

        } else {
            Log.d(TAG, "Error getting document.", task.getException());
        }
    }
});

// Get a subcollection
docRef.collection("friends_list").get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (DocumentSnapshot document : task.getResult()) {
                        Log.d(TAG, document.getId() + " => " + document.getData());
                    }
                } else {
                    Log.d(TAG, "Error getting subcollection.", task.getException());
                }
            }
        });
like image 94
Sam Stern Avatar answered Oct 13 '22 01:10

Sam Stern