繁体   English   中英

如何将文档上传到 Firestore

[英]How to upload documents to Firestore

有一个关于从 Firebase Firestore Cloud 加载数据的问题。 有一个简单的查询:

val firestore = Firebase.firestore

suspend fun getDocuments(timestamp: Timestamp): List<Entity> =
   firestore
      .collection("collection")
      .orderBy("modified_at", Query.Direction.ASCENDING)
      .whereGreaterThan("modified_at", timestamp)
      .get()
      .await()
      .toObjects(Entity::class.java)

如果上传文件时出现问题怎么办? 我会收到不完整的数据或错误吗?

文件按什么顺序加载? orderBy 会影响加载顺序吗?

如果上传文件时出现问题怎么办?

据我所知,您没有上传任何文档,您只是使用get()阅读它们:

执行查询并将结果作为 QuerySnapshot 返回。

在 Firestore 中执行 CRUD 操作时,总是存在操作失败的可能性,例如,由于不正确的安全规则。 话虽如此,始终建议处理错误。 所以你的方法应该包含一个 try-catch 如下所示:

suspend fun getDocuments(timestamp: Timestamp): List<Entity> {
    return try {
        firestore
            .collection("collection")
            .orderBy("modified_at", Query.Direction.ASCENDING)
            .whereGreaterThan("modified_at", timestamp)
            .get()
            .await()
            .toObjects(Entity::class.java)
    } catch (e: Exception) {
        throw e
    }
}

然而,更优雅的解决方案是使用包含两个字段、数据和异常的 class。 以下资源中解释了这种做法:

文件按什么顺序加载?

您可以根据作为参数传递给orderBy()方法的内容对文档进行排序。

orderBy 会影响加载顺序吗?

当然,这就是我们使用它的原因,有一个特定的顺序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM