我有一些关于 Firebase Firestore 的具体问题。我有一个像这样的 Firestore 示例模型:
类别是一些文档内的集合。我尝试从集合中获取所有文档,如下所示:
query.addSnapshotListener { querySnapshot, firebaseFirestoreException ->
if (firebaseFirestoreException != null) {
if (!emitter.isDisposed) {
TODO("implement new exception logic")
}
} else {
val value = querySnapshot.toObjects(Category::class.java)
}
}
在这种情况下,我得到Category
文档列表。
我可以像这样创建类 CategoriesEntity
并在 addSnapshotListener
中获取此模型类吗?
public class CategoriesEntity {
private Map<String, Category> categories;
public CategoriesEntity() {
}
public Map<String, Category> getCategories() {
return categories;
}
public void setCategories(Map<String, Category> categories) {
this.categories = categories;
}
}
最佳答案
没有像 toObjects()
这样的便捷方法可以创建 map ,但您可以手动迭代每个文档并将其添加到 map 中。
集合中的文档以列表形式返回,因此您可以迭代每个文档,将其转换为 Category
实例,然后手动将其添加到 map 中,如下所示:
query.addSnapshotListener { querySnapshot, firebaseFirestoreException ->
if (firebaseFirestoreException != null) {
if (!emitter.isDisposed) {
TODO("implement new exception logic")
}
} else {
val categories = HashMap<String, Category>()
for (document in querySnapshot.getDocuments()) {
categories.put(document.getId(), document.toObject(Category::class.java))
}
val categoriesEntity = CategoriesEntity()
categoriesEntity.setCategories(categories)
}
}
关于java - 如何从 POJO 类中的 Firestore 集合中检索所有文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47433917/