【问题标题】:Swift Firebase database overwritingSwift Firebase 数据库覆盖
【发布时间】:2019-04-28 11:14:06
【问题描述】:

我正在使用 Firebase 制作实时信使。目前,每当我按下按钮时,我都希望将一条带有消息索引的新消息附加到频道中,但目前,每当我按下按钮时,都会创建一条覆盖旧消息的新消息。我知道 setValue 通常是问题所在,但我真的不知道我做错了什么。 What the database looks like before I add my new message。这是我添加一条新消息here,然后是我用来添加到数据库的代码后的样子。

@IBAction func sendMessageTapped(_ sender: Any) {
    if messageTextField.text == "" {
        print("blank")
        return
    } else {
        // First we will update the amount of messages that the channel has.
        ref.child("channels").child(channelName!).setValue(["numberOfMessages" : numberOfMessages+1 ])
        numberOfMessages += 1
        // after we have updated the amount of messages we will try to create a new message.
        ref.child("channels").child(channelName!).child("messages").child(String(numberOfMessages)).child("message").child("content").setValue(messageTextField.text)
        ref.child("channels").child(channelName!).child("messages").child(String(numberOfMessages)).child("message").child("name").setValue("Buddy")

    }
}

【问题讨论】:

  • 有几件事:a) 不要在 NoSQL 数据库中使用数字索引。这本质上是一个数组和Arrays Are Evil。 b)您每次都覆盖消息节点,这就是为什么您只有一个节点。

标签: ios swift firebase firebase-realtime-database overwrite


【解决方案1】:

好的,Firebase 不是传统的基于表的数据库,而是基于 DOCUMENT 的数据库。在最顶部,您有一个称为“集合”的东西,它只是“文档”事物的列表。在您的情况下,您将有几个集合内容作为渠道:“General”、“TopicQ”、“InterstingStuff”等,其中每条消息都作为文档。无需文档,然后列出其中的消息。

其次,您在使用它们时不需要索引,将消息 id 作为消息的属性,因为 firebase 支持按字段查询,即使这样也是有问题的,因为如果您将每条消息都设为文档,它们如果您愿意,将有自己的自动生成的 ID。

第三,在您的代码中,您每次都在重写整个文档,这就是您丢失之前消息的原因,因此如果您保留它,则需要添加一个合并选项:

// Update one field, creating the document if it does not exist.
db.collection("cities").document("BJ").setData([ "capital": true ], merge: true)

【讨论】:

  • OP 使用的是 Firebase 数据库,而不是 Firestore。 Firebase 数据库没有集合和文档;只是直接的 JSON 存储。另外,数据库中没有合并功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-07
  • 1970-01-01
  • 1970-01-01
  • 2017-07-18
相关资源
最近更新 更多