【问题标题】:I am developing an android app with Kotlin and I am trying to get document reference from Firestore我正在使用 Kotlin 开发一个 android 应用程序,我正在尝试从 Firestore 获取文档参考
【发布时间】:2020-02-26 16:16:59
【问题描述】:

我正在使用 Kotlin 和 Firebase 开发一个 android 本机应用程序,我有一个名为 Topic 的集合和 2 个类型参考字段,一个用于 User,另一个用于 Category,我试图通过参考文档获取所有文档,但是它似乎不起作用:

db.collection("topic").get().addOnSuccessListener { result ->
        for (document in result) {
            Log.e("success", "${document.id} => ${document.data.get("subject")}")
            var topic: Topic = Topic(
                document.id as String,
                document.data.get("subject") as String,
                document.data.get("content") as String,
                document.data.get("created_at") as String,
                document.getDocumentReference("Category") as Category,
                document.getDocumentReference("User") as User
            )}

没有错误,但在我的 print(topic) 中也没有结果。

这是主题类

class Topic : Serializable {
    var id : String = ""
    var subject : String = ""
    var content : String = ""
    var created_at : String = ""
    var cat = Category()
    var user = User()

    constructor(){}

    constructor(
        id: String,
        subject: String,
        content: String,
        created_at: String,
        cat: Category,
        user: User
    ) {
        this.id = id
        this.subject = subject
        this.content = content
        this.created_at = created_at
        this.cat = cat
        this.user = user
    }

    override fun toString(): String {
        return "Topic(id='$id', subject='$subject', content='$content', created_at='$created_at', cat=$cat, user=$user)"
    }
}

【问题讨论】:

  • 请将您的数据库结构添加为屏幕截图和Topic 类的内容。
  • 嗨,对不起,我应该提供的,我添加了类和数据库结构。

标签: android firebase kotlin google-cloud-firestore


【解决方案1】:

您必须通过单独的get() 调用显式获取每个引用的文档。无法在您当前的通话中自动获取它们。

比如:

db.collection("topic").get().addOnSuccessListener { result ->
    for (document in result) {
        document.getDocumentReference("Category").get().addOnSuccessListener { categoryDoc ->
            let category = categoryDoc.data as Category
            ...
        }
    }
}

另见:

【讨论】:

  • 感谢@Frank van Puffelen 的回复,尤其是您解释我应该做什么的代码。
【解决方案2】:

当您使用以下代码行时:

document.getDocumentReference("Category") as Category

你得到的是一个DocumentReference 类型的对象,而不是一个Category 类型的对象,因为 DocumentSnapshot 的getDocumentReference() 方法返回了那种类型的对象。请记住,在 Kotlin 中,您无法将 DocumentReference 类型的对象强制转换为 Category,因此会出现这种行为。

因此,简单地获取对象的引用将返回对象本身的假设是正确的。正如@FrankvanPuffelen 在他的回答中提到的那样,您可以解决这个问题的唯一方法是为每个人单独调用。

作为一个单独的主题,您还可以从下面的帖子中查看我的答案,因为我看到您对文档中的属性使用了不同的命名:

【讨论】:

  • 感谢@Alex Mamo 的回答,它帮助我理解了 DocumentReference 的概念。
  • 不客气,CHARFEDDINE!我的回答是对@FrankvanPuffelen 回答的内容的补充。
猜你喜欢
  • 2020-12-09
  • 2020-03-30
  • 1970-01-01
  • 2019-08-31
  • 2018-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多