【问题标题】:unwanted ghost data appearing on firebase firestoreFirebase Firestore 上出现不需要的幽灵数据
【发布时间】:2021-07-08 12:43:13
【问题描述】:

我在嵌套集合上创建 Firestore 文档,因此要创建文档需要在文档上放置一些数据。我正在放置不同的数据,但在设备和模拟器中出现了其他不变的数据。为什么会这样?文档对此有何评论以及应该如何删除它?

代码:

//userPlace is the firestore doc path.
userPlace.set({ "Hi" to "Hello" }).addOnSuccessListener {
                    userPlace.collection("what").document("what").set("docData")
                }

此代码生成的数据在 userPlace 文档路径中显示为 arity : 0

【问题讨论】:

  • userPlace 是否仍定义为val userPath = db.collection("Users").document(who) .collection("UsersActivity").document("history").set(docData)
  • 路径无关紧要。即使db.collection("Users").document("history").set({ "Hi" to "Hello" }),我也得到了相同的结果。

标签: firebase kotlin google-cloud-firestore


【解决方案1】:

要将数据写入 Firestore,您有两种选择。第一个是创建一个自定义类:

data class Chat(
    var message: String? = null
)

要将消息写入数据库,您应该使用以下代码行:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance()
CollectionReference chatsRef = rootRef.collection("chats")
DocumentReference chatIdRef = chatsRef.document("someChatId")
chatIdRef.set(Chat("Hello"))

此代码将生成此架构:

Firestore-root
  |
  --- chats (collection)
       |
       --- someChatId (document)
            |
            --- message: "Hello"

您拥有的第二个选项是使用地图:

chatIdRef.set(mapOf("message" to "Hello"))

此代码将生成与上述相同的架构。

但是,如果您只将以下代码块传递给set() 方法:

 .set({ "Hi" to "Hello" })

Firestore 不会将其识别为特定类的对象,也不会识别为 Map。在这种情况下,Firestore 添加了一个名为 arity 的字段,其中包含一个默认值为 0 的数字。

另外,上面的代码还可以写成:

.set( "Hi" to "Hello" ) //Without curly braces

这将产生不同的 Firestore 架构:

Firestore-root
  |
  --- chats (collection)
       |
       --- someChatId (document)
            |
            --- first: "Hi"
            |
            --- second: "Hello"

现在,为了避免所有这些情况,您绝对应该根据需要使用第一个或第二个选项,将一致的数据写入 Firestore。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    相关资源
    最近更新 更多