java - 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!
解决方案
要解决此问题,请更改以下代码行:
firestore.collection("shop/").document("warehouse").addSnapshotListener(/* ... */);
至
firestore.collection("shop").document("warehouse").addSnapshotListener(/* ... */);
没有必要这样做/
。您"shop/warehouse"
只能在 Firebase Realtime 数据库中使用这样的引用,其中所有对象都称为子对象,并且您可以将所有子对象链接在单个路径中。这是一种更优雅的方式,但不幸的是,Cloud Firestore 不允许这样做。
推荐阅读
- python - 嗨,我在使用中断功能时遇到错误
- server - 仍然在服务器上收到消息(imapd)从 xxx.xxx.xxx.xxx(CID/国家/-)的 IMAP 登录失败,即使我已经从任何软件中注销
- html - 如何在上传文件(primeng)之前要求确认?
- c - 使用 callgrind 或程序集修改优化嵌套 if 和 switch 语句
- node.js - Express 静态网络请求停留在“未决”状态
- python - Python KeyError:'destinationAccount'
- postgresql - 无法将 Json 数组插入 PostgreSQL,因为左括号丢失错误
- python - 如何将缩放的数据帧转换回原始数据,本质上类似于 Python 中的缩放操作
- python-3.x - 更新的列表不会在 Python 中使用
- java - 使用 Apache POI Java 将多个 excel 文件合并为一个 excel 文件