我正在处理一个项目,该项目采用swift 4中以下语句编写的数据:
@IBAction func saveButton(_ sender: Any) {
db.collection("violets").document(plantName.text!).setData([
"Plant Name": "\(plantName.text ?? "")",
"Hybridizer": "\(hybridizer.text ?? "")",
"Registration Number": Int("\(registrationNumber.text ?? "")"),
"Type": "\(type.text ?? "")",
"Description": "\(generalDescription.text ?? "")",
"Notes": "\(notes.text ?? "")"
]) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("Document successfully written!")
}
}
uploadImage(violetImage.image!)
}
这已成功写入我的FireStore:
我的问题是在添加更多数据时,很容易覆盖FireStore中的现有文档。我认为解决此问题的最佳方法是实现限制覆盖数据的特定权限。
我希望在用户经过身份验证以及文档名称是否已经存在于数据库中时,尝试仅允许覆盖。
这是我的FireStore权限配置:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read : if request.auth.uid != null;
//allow write: if request.auth.uid != null && !data.exists
}
match /violets/{violetID} {
allow write: if !exists(violetID)
}
}
}
此时只是否定所有写作期。我误解了FireStore的文件结构还是其他错误的东西?
编辑:想想我离得更近但仍然没有雪茄......
答案 0 :(得分:0)
所以我从来没有真正能够获得权限验证本身的工作;但我找到了一种方法,通过验证我试图写入的文档是否存在来在代码中完成。这是我的最终解决方案:
@IBAction func saveButton(_ sender:Any){
let docRef = db.collection("violets").document(plantName.text!)
docRef.getDocument { (document, err) in
guard
let document = document,
let user = document.exists ? document : nil
else {
print("Plant does not exist in DB. Writting new Entry")
self.db.collection("violets").document(self.plantName.text!).setData([
"PlantName": "\(self.plantName.text ?? "")",
"Hybridizer": "\(self.hybridizer.text ?? "")",
"Registration Number": Int("\(self.registrationNumber.text ?? "")"),
"Type": "\(self.type.text ?? "")",
"Description": "\(self.generalDescription.text ?? "")",
"Notes": "\(self.notes.text ?? "")"
]) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("Document successfully written!")
}
}
self.violetImage.image = self.violetImage.image?.resizeWithWidth(width: 120)
self.uploadImage(self.violetImage.image!)
self.itemFinishedAdding()
return
}
print("\(self.plantName.text!) is already in the database")
}
}
虽然这种逻辑有效但我对此并不十分满意。还是Chuggin'在它。