Skip to content

Commit f48dea1

Browse files
samtsternkurtisvg
authored andcommitted
Add Firestore snippet for getCollections() (#988)
* Add snippet for Collections() * Fix test failures
1 parent 387b1d1 commit f48dea1

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

firestore/src/main/java/com/example/firestore/snippets/RetrieveDataSnippets.java

+17
Original file line numberDiff line numberDiff line change
@@ -137,4 +137,21 @@ public List<DocumentSnapshot> getAllDocuments() throws Exception {
137137
// [END fs_get_all_docs]
138138
return documents;
139139
}
140+
141+
/**
142+
* Return all subcollections of the cities/SF document.
143+
*
144+
* @return iterable of collection references.
145+
*/
146+
public Iterable<CollectionReference> getCollections() throws Exception {
147+
// [START fs_get_collections]
148+
Iterable<CollectionReference> collections =
149+
db.collection("cities").document("SF").getCollections();
150+
151+
for (CollectionReference collRef : collections) {
152+
System.out.println("Found subcollection with id: " + collRef.getId());
153+
}
154+
// [END fs_get_collections]
155+
return collections;
156+
}
140157
}

firestore/src/test/java/com/example/firestore/snippets/RetrieveDataSnippetsIT.java

+22
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,13 @@
2222
import com.example.firestore.snippets.model.City;
2323

2424
import com.google.api.core.ApiFuture;
25+
import com.google.cloud.firestore.CollectionReference;
2526
import com.google.cloud.firestore.DocumentSnapshot;
2627
import com.google.cloud.firestore.Firestore;
2728
import com.google.cloud.firestore.FirestoreOptions;
2829
import com.google.cloud.firestore.QuerySnapshot;
30+
import java.util.ArrayList;
31+
import java.util.HashMap;
2932
import java.util.HashSet;
3033
import java.util.List;
3134
import java.util.Map;
@@ -99,6 +102,25 @@ public void testRetrieveAllDocuments() throws Exception {
99102
&& docIds.contains("BJ"));
100103
}
101104

105+
@Test
106+
public void testGetSubcollections() throws Exception {
107+
// Add a landmark subcollection
108+
Map<String, String> data = new HashMap<>();
109+
data.put("foo", "bar");
110+
db.document("cities/SF/landmarks/example").set(data).get();
111+
112+
Iterable<CollectionReference> collections =
113+
retrieveDataSnippets.getCollections();
114+
115+
List<CollectionReference> collectionList = new ArrayList<>();
116+
for (CollectionReference collRef : collections) {
117+
collectionList.add(collRef);
118+
}
119+
120+
assertEquals(collectionList.size(), 1);
121+
assertEquals(collectionList.get(0).getId(), "landmarks");
122+
}
123+
102124
private static void deleteAllDocuments() throws Exception {
103125
ApiFuture<QuerySnapshot> future = db.collection("cities").get();
104126
QuerySnapshot querySnapshot = future.get();

0 commit comments

Comments
 (0)