Skip to content

Commit

Permalink
Add Firestore snippet for getCollections() (#988)
Browse files Browse the repository at this point in the history
* Add snippet for Collections()

* Fix test failures
  • Loading branch information
samtstern authored and kurtisvg committed Jan 11, 2018
1 parent 387b1d1 commit f48dea1
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -137,4 +137,21 @@ public List<DocumentSnapshot> getAllDocuments() throws Exception {
// [END fs_get_all_docs]
return documents;
}

/**
* Return all subcollections of the cities/SF document.
*
* @return iterable of collection references.
*/
public Iterable<CollectionReference> getCollections() throws Exception {
// [START fs_get_collections]
Iterable<CollectionReference> collections =
db.collection("cities").document("SF").getCollections();

for (CollectionReference collRef : collections) {
System.out.println("Found subcollection with id: " + collRef.getId());
}
// [END fs_get_collections]
return collections;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,13 @@
import com.example.firestore.snippets.model.City;

import com.google.api.core.ApiFuture;
import com.google.cloud.firestore.CollectionReference;
import com.google.cloud.firestore.DocumentSnapshot;
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.FirestoreOptions;
import com.google.cloud.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -99,6 +102,25 @@ public void testRetrieveAllDocuments() throws Exception {
&& docIds.contains("BJ"));
}

@Test
public void testGetSubcollections() throws Exception {
// Add a landmark subcollection
Map<String, String> data = new HashMap<>();
data.put("foo", "bar");
db.document("cities/SF/landmarks/example").set(data).get();

Iterable<CollectionReference> collections =
retrieveDataSnippets.getCollections();

List<CollectionReference> collectionList = new ArrayList<>();
for (CollectionReference collRef : collections) {
collectionList.add(collRef);
}

assertEquals(collectionList.size(), 1);
assertEquals(collectionList.get(0).getId(), "landmarks");
}

private static void deleteAllDocuments() throws Exception {
ApiFuture<QuerySnapshot> future = db.collection("cities").get();
QuerySnapshot querySnapshot = future.get();
Expand Down

0 comments on commit f48dea1

Please sign in to comment.