Firestore - How Can I Get The Collections From a D

2019-06-07 07:48发布

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?

1条回答
冷血范
2楼-- · 2019-06-07 08:05

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());
                }
            }
        });
查看更多
登录 后发表回答