首页 > 解决方案 > 为什么 Firestore DocumentSnapshot.exist() 总是`false` addOnCompleteListener?

问题描述

我正在创建基本应用程序以从 Firestore 检索用户数据,如果用户是新用户(在 Firestore 中,即文档不应该存在),我将添加欢迎说明(一些默认数据到 DB)。

private fun createUserIfNeeded(user: FirebaseUser) {
    fireBaseFireStore.collection("Users").document(user.uid).get().addOnCompleteListener {
        if (it.isSuccessful && !it.result!!.exists()) {
            val defaultData = 
                hashMapOf("head" to "Hello", "body" to "Welcome to NoteIt...")

            fireBaseFireStore
                .collection("Users")
                .document(user.uid)
                .collection("Notes")
                .document("Default")
                .set(defaultData)
        }
    }
}

当我运行上面的代码时,即使文档存在document.result.exist也总是如此。false

我也尝试使用addOnSuccessListener相同的结果。

难道我做错了什么?

我提到了许多与此相关的问题,但解决方案有所帮助。

PS:Firebase 及其 API 的新手

更新:如果我试图检查任何内部集合和文档,那么结果工作正常

private fun createUserIfNeeded(user: FirebaseUser) {
        val notesRef = fireBaseFireStore
            .collection("Users")
            .document(user.uid)
            .collection("Notes")

        notesRef
            .get()
            .addOnCompleteListener {
                if (it.result == null || it.result!!.documents.size == 0) {
                    val defaultData = hashMapOf("head" to "Hello", "body" to "Welcome to NoteIt...")
                    notesRef
                        .document("Default")
                        .set(defaultData)
                }
            }
    }

我无法理解问题所在。

标签: androidfirebasegoogle-cloud-firestore

解决方案


试试这个,卸载应用程序并重新安装,有时需要刷新你的数据库的 Firestore 本地缓存版本,在开发期间

开发时可能会在 Firestore 控制台中错误地查看错误的数据库,假设您的应用程序有开发者版本和生产版本,喝咖啡时可能会看到错误的东西


推荐阅读