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?
You can do the following: const admin = require("firebase-admin"); const db = admin. firestore(); db. listCollections() .
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.
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());
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With