Reputation: 4277
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?
Upvotes: 6
Views: 4992
Reputation: 25134
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());
}
}
});
Upvotes: 11