【问题标题】:How to retrieve all documents from Firestore collection in POJO class?如何从 POJO 类的 Firestore 集合中检索所有文档?
【发布时间】:2017-11-22 11:46:14
【问题描述】:

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

Categories 是集合,在一些文档中。我尝试像这样从集合中获取所有文档:

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;
    }
}

【问题讨论】:

    标签: java kotlin google-cloud-firestore


    【解决方案1】:

    没有像toObjects() 这样可以创建地图的便捷方法,但您可以手动遍历每个文档并将其添加到地图中。

    集合中的文档以列表形式返回,因此您可以遍历每个文档,将其转换为 Category 实例并手动将其添加到您的地图中,如下所示:

    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)
        }
    }
    

    【讨论】:

    • 谢谢,也许这是迄今为止唯一的解决方案。
    • 我相信是这样,因为toObjects() 方法基本上是一种方便的方法,用于为您执行for (document in snapshot.getDocuments()) document.toObject() 的逻辑和迭代,但它以列表的形式返回。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    相关资源
    最近更新 更多