java - 如何从 POJO 类中的 Firestore 集合中检索所有文档?

标签 java kotlin google-cloud-firestore

我有一些关于 Firebase Firestore 的具体问题。我有一个像这样的 Firestore 示例模型:

Firestore screenshot

类别是一些文档内的集合。我尝试从集合中获取所有文档,如下所示:

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/

相关文章:

android - 在 Android 上使用 FirebaseUI 的 GitHub oAuth

android - Firebase Unresolved reference

javascript - 递归更新子集合/collectionGroup 的 Firestore 云函数

javascript - 使用 firebase 身份验证和 firestore 添加用户

java - 使用 Spring-batch-excel 读取 Excel 时出错

java - JOGL 过剩文本不随窗口和基元调整大小

Java 错误 - 需要数组,但找到了 java.lang.String

java - Kotlin\Java - 如何获取已更改数组元素的总和

java - 如何返回 DocumentSnapShot 作为方法的结果?

java - Rx Java zip 在任何主题完成时完成