首页 > 解决方案 > Firebase Cloud Firestore - 从偶数个段中获取集合

问题描述

我有一个这样的数据库Shop > warehouse > categories > cat1,cat2,..,每个类别都有一个名称和它的文档。我只想要类别,我尝试使用以下代码:

firestore.collection("shop/warehouse").addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(@javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots, @javax.annotation.Nullable FirebaseFirestoreException e) {
            if(queryDocumentSnapshots != null) {
                for (DocumentSnapshot doc : queryDocumentSnapshots) {
                    String item = doc.getId();
                    Log.d("TEST ITEM", item);
                }
            } else Log.d(TAG, "queryDocumentSnapshots is null.");
        }
    });

但正如预期的那样,我收到了这个错误:

Invalid collection reference. Collection references must have an odd number of segments, but shop/warehouse has 2

所以我用谷歌搜索并找到了一个建议划分集合/文档的解决方案,我写了这个:

firestore.collection("shop/").document("warehouse").addSnapshotListener(new EventListener<DocumentSnapshot>() {
        @Override
        public void onEvent(@javax.annotation.Nullable DocumentSnapshot documentSnapshot, @javax.annotation.Nullable FirebaseFirestoreException e) {
            Map<String, Object> map = documentSnapshot.getData();
            Log.d("size", map.keySet().size()+"");
        }

但是这个键集(我假设它们是类别名称)是空的。我该怎么做?可怜我吧,这是我第一次使用 Firebase!

标签: javaandroidfirebasegoogle-cloud-firestore

解决方案


要解决此问题,请更改以下代码行:

firestore.collection("shop/").document("warehouse").addSnapshotListener(/* ... */);

firestore.collection("shop").document("warehouse").addSnapshotListener(/* ... */);

没有必要这样做/。您"shop/warehouse"只能在 Firebase Realtime 数据库中使用这样的引用,其中所有对象都称为子对象,并且您可以将所有子对象链接在单个路径中。这是一种更优雅的方式,但不幸的是,Cloud Firestore 不允许这样做。


推荐阅读