【问题标题】:How to store data in Firestore (Swift)如何在 Firestore (Swift) 中存储数据
【发布时间】:2018-04-29 17:54:17
【问题描述】:

我有一个使用 Cloud Firestore 的 iOS 应用,但在更新数据时遇到了问题。我的目标是将网址一一添加到字典中,但我得到的只是重写一个值。我应该如何使用 setData 和 updateData?尝试了不同的方法

storageRef.child("users/" + currentUser.value!.documentID + "/" + faceRef.documentID + ".jpg")
          .putData(data!).observe(.success) { (snapshot) in

        guard let downloadURL = snapshot.metadata?.downloadURL()?.absoluteString else { return }
        let db = self.fsReference.document(self.currentUser.value!.documentID)
        var dict = ["faces": ["": ""]]
        dict["faces"] = ["newvalue\(downloadURL.hashValue)": downloadURL]

        db.updateData(dict)
        completion?()

这是我尝试过的。任何建议都会很好,在此先感谢!

UPD:尝试将我的字典移动到子集合,但在 .collection("newCollection").document("newdocument") 之后集合没有出现。可能是什么问题?

【问题讨论】:

  • 嗨,马克斯。当您进行这样的更新时,您将最终“替换”该对象。解决方案可能是将 url 存储在子集合中?
  • 感谢您的回复!目前子集合存在问题,当我执行.collection("newcollection").document("newDocument") 之类的操作时它们不会出现,当我放入数据时,数据库没有任何反应。你觉得可能是什么问题?
  • 您使用的是完整路径吗?如果您要将其保存在用户文档中,应如下所示:users/${currentUserId}/urlCollection/${idOnNewDoc} --> 有意义吗?
  • 好吧,我最终想通了。代码中有一些方法可以设置模型并更新 Firestore。那不是我的代码,所以我遇到了这个困难)

标签: swift firebase google-cloud-firestore


【解决方案1】:

所以我看到的是您正在使用云存储来保存个人资料图片,并且您希望保存这些图片的每一个网址。您需要了解 setValue()updateValue() 做的事情几乎相同。 updateValue() 的说明是,如果该文档尚不存在,它将创建该文档。因此,当在 Firestore 中更新值时,请了解它会将值设置为您给它的值,这起初可能会产生误导。

1st 更新任何文档时,首先获取文档。如果人们不断更新不同的文档,您可能需要考虑使用 Firestore 事务:https://firebase.google.com/docs/firestore/manage-data/transactions#transactions 这将确保您的数据正确更新。

2nd 将 URL 附加到数组中,我不是你设置它的方式,但我会设置 firestore 看起来像这样

"users" = [
    "unique_id = "{
        "firstname": "John",
        "lastname": "Doe",
        "unique_id": "document_id_here"
        "faces": [ {key: value} ]
    }
]

当你序列化那个对象时,你的 faces 对象应该是这个 [[String: Any]]

第三步,最后一步是获取文档并仅更新该值

// Get the value in the completion with the data use this code
// Drill down to the property you want to update using the completion data ex.
var faces = completedData.faces
faces.append("[key: value]") 


// Update the data back to firestore

let path = Firestore.firestore().collection("users").document("unique_user_id")

// Merging is so important. otherwise it will override your document 
path.setData(["facesKey: faces"], merge: true) {(error in
   if let error = error {
      // good error handling here
    }

    // Successfully updated document 

)} 

【讨论】:

    猜你喜欢
    • 2019-03-26
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    相关资源
    最近更新 更多