如何在Firestore(Swift)中存储数据
我有一个使用Cloud Firestore的iOS应用程序,在更新数据时遇到问题。我的目标是一个接一个地将URL添加到字典中,但我得到的只是重写一个值。我应该如何使用setData和updateData?试过不同的方法如何在Firestore(Swift)中存储数据,swift,firebase,google-cloud-firestore,Swift,Firebase,Google Cloud Firestore,我有一个使用Cloud Firestore的iOS应用程序,在更新数据时遇到问题。我的目标是一个接一个地将URL添加到字典中,但我得到的只是重写一个值。我应该如何使用setData和updateData?试过不同的方法 storageRef.child("users/" + currentUser.value!.documentID + "/" + faceRef.documentID + ".jpg") .putData(data!).observe(.success) {
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”)之后。文档(“newdocument”)
集合未出现。可能有什么问题?所以我看到的是,您正在使用云存储来保存配置文件图片,并且希望保存这些图片中的每个URL。您需要了解setValue()和updateValue()做的事情大致相同。updateValue()的一个注释是,如果该文档不存在,它将创建该文档。因此,当更新Firestore中的值时,请理解它会将值设置为您提供的值,这可能会在一开始产生误导
第一,更新任何文档时,首先获取文档。如果人们不断更新不同的文档,您可能需要考虑使用FixSt店事务:
这将确保您的数据正确更新
第二,将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
)}
Hi Max.当您执行这样的更新时,您将“替换”对象。解决方案是将URL存储在子集合中?感谢您的回复!目前,子集合存在问题,当我执行类似于
.collection(“newcollection”).document(“newDocument”)
的操作时,它们不会出现,并且当我放置数据时,数据库不会发生任何变化。你认为可能是什么问题?你在使用完整路径吗?如果要将其保存在用户文档中,应该如下所示:users/${currentUserId}/urlCollection/${idOnNewDoc}
-->这有意义吗?我最终找到了答案。代码中有一些方法用于设置模型和更新firestore。这不是我的代码,所以我遇到了这些困难)