Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add snippet for getCollections() #988

Merged
merged 2 commits into from
Jan 11, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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