【问题标题】:Firebase Cloud Firestore - Get a collection from an even number of segmentsFirebase Cloud Firestore - 从偶数个段中获取集合
【发布时间】:2018-11-07 12:26:43
【问题描述】:

我有一个像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

所以我用谷歌搜索并找到了a solution that suggests to divide in collection/document,然后我写了这个:

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!

【问题讨论】:

标签: java android firebase google-cloud-firestore


【解决方案1】:

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

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

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

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

【讨论】:

  • 您在使用firestore.collection("shop").document("warehouse")时遇到此错误Invalid collection reference. Collection references must have an odd number of segments, but shop/warehouse has 2
  • 一切都好吗,你解决了吗?
  • 不,遗憾的是我仍然收到此错误,删除 '\' 没有任何变化
  • 能否请您添加您的数据库结构。
  • 看到你的整个数据库结构,我可以说你不能只得到那些没有查询数据库的ID。正如 Doug 所说,您需要查询整个数据库以读取集合中的所有这些文档,以便仅获取这些 id。
【解决方案2】:

没有 API 可以仅列出集合中存在的文档 ID。您必须查询并阅读集合中的所有文档才能获取 ID。

【讨论】:

  • 我不知道您所说的“蛮力”是什么意思,但正如我在回答中所说,您将不得不查询整个集合,阅读所有文档并获取它们的所有 ID。
  • 对不起,我的意思是通过硬编码来做,因为当我查询文档时,我没有得到任何数据,这里是一个例子(对不起质量非常低,我不知道为什么这么差) imgur.com/a/gNcxG5Y
  • 无论你在那里做什么看起来都与原始问题无关,
猜你喜欢
  • 1970-01-01
  • 2018-03-24
  • 2021-05-06
  • 2018-04-30
  • 2019-12-24
  • 1970-01-01
  • 2021-05-09
  • 2019-03-12
相关资源
最近更新 更多