如何在Firestore中检索子集合的文档? [英] How to retrieve documents of a sub collection in Firestore?
问题描述
我有一个数据库,其结构如下图所示:
I have a db with structure like in the image below:
在这里,我需要拥有多个品牌,并且每个品牌下还需要多个子品牌.我以前尝试过使用地图",但是确实很乱,并且还了解到拥有多个文档会更好.我对此很陌生,并且已经为此奋斗了3-4天.任何帮助将不胜感激.
Here, I need to have multiple brands, and also multiple sub brands under each brand. I tried with 'maps' before, but it was really messy and also learned that it's better to have multiple documents. I am very new to this and has been struggling with it for 3-4 days now. Any help would be much appreciated.
firebaseFirestore.collection("Coffee").addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (e != null) {
Log.d(TAB, "Error : " + e.getMessage());
}
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
Log.d("Brand Name: ",doc.getDocument().getId());
// how to retrieve documents of subCollection here? something like doc.getDocument().collection??
}
}
}
});
谢谢.
推荐答案
这真的很简单,尝试一下.
This is really simple and easy try this.
firebaseFirestore.collection("Coffee").addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (e != null) {
Log.d("", "Error : " + e.getMessage());
}
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
Log.d("Brand Name: ", doc.getDocument().getId());
doc.getDocument().getReference().collection("SubBrands").addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (e != null) {
Log.d("", "Error : " + e.getMessage());
}
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
Log.d("SubBrands Name: ", doc.getDocument().getId());
}
}
}
});
}
}
}});
注意:我已经更新了答案.显然,您无法通过单个请求来获取集合文档中的子集合.
Note: i have updated the answer. It is obvious that you can't fetch sub collections within the collection's document with a single request.
这篇关于如何在Firestore中检索子集合的文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!