【问题标题】:How to delete a document from firestore if it exists in swift?如果它存在于swift中,如何从firestore中删除文档?
【发布时间】:2020-09-15 07:52:31
【问题描述】:

我正在尝试验证用户是否已经 以前喜欢或不喜欢一家商店。如果他不这样做,它会将数据添加到 Firestore 集合中,否则如果他再次单击它会删除它。

现在每次我点击它添加一个新文档的按钮时,如果他再次点击,我无法弄清楚如何删除现有文档。

@IBAction func tapFaveBtn(_ sender: Any) {
        
        
        let name = shopName.text!
        let address = detailedAdress.text!
        let table = numTable.text!
        let summaryS = summary.text!
        let timingS = timing.text!
        let userID = Auth.auth().currentUser!.uid
        
        db.collection("Favorites").whereField("shopPID", isEqualTo: getKey!).
        whereField("userID", isEqualTo: userID).
        getDocuments(){
                querySnapshot, error in
                if let error = error {
                    print(error.localizedDescription)
                }else
                {
                    if((querySnapshot!.isEmpty)){
                    self.db.collection("Favorites").addDocument(data:[
                    "ShopHeaderImg": self.headerImgURL!,
                    "ShopProfileImg":"",
                    "address": address,
                    "costEst": self.costEst.text!,
                    "country": "",
                    "latitude": self.getFinalLatitude!,
                    "location": self.location!,
                    "longitude": self.getFinalLongitude!,
                    "name": name,
                    "numTables": table,
                    "shopPID": self.getKey!,
                    "summary": summaryS,
                    "timing": timingS,
                    "usersID": userID,
                    ])
                   print("saved")
                                                          
                    }else {
           for document in querySnapshot!.documents{
          document.reference.delete()
                  }
                    }
                }
                }
            }
    }

对此有什么帮助吗?谢谢

【问题讨论】:

  • 您正在使用whereField("userID", isEqualTo: userID) 查询您的数据库,但是当您添加一个新文档时,您指定usersID 这就是问题所在。更改任一字段键以正确查询
  • @Ryohei 非常感谢,这是我 whereField 中的错字。谢谢指出!!!

标签: ios swift google-cloud-firestore


【解决方案1】:

您正在向Firebase 发送嵌套请求(第一个:getDocuments,第二个:addDocumentdelete)。将您的代码更改为:

var isExist: Bool = false {
      didSet{
          setDocument()
      }
}

@IBAction func tapFaveBtn(_ sender: Any) {
        
    
    let name = shopName.text!
    let address = detailedAdress.text!
    let table = numTable.text!
    let summaryS = summary.text!
    let timingS = timing.text!
    let userID = Auth.auth().currentUser!.uid
    
    db.collection("Favorites").whereField("shopPID", isEqualTo: getKey!).
    whereField("userID", isEqualTo: userID).
    getDocuments(){
            querySnapshot, error in
            if let error = error {
                print(error.localizedDescription)
            }else
            {
                if((querySnapshot!.isEmpty)){
                    self.isExist = true
            }
            }
        }
}

func setDocument(){ 
    if self.isExist{
        self.db.collection("Favorites").addDocument(data:[
             "ShopHeaderImg": self.headerImgURL!,
             "ShopProfileImg":"",
             "address": address,
             "costEst": self.costEst.text!,
             "country": "Bahrain",
             "latitude": self.getFinalLatitude!,
             "location": self.location!,
             "longitude": self.getFinalLongitude!,
             "name": name,
             "numTables": table,
             "shopPID": self.getKey!,
             "summary": summaryS,
             "timing": timingS,
             "usersID": userID,
          ])
           print("saved")

    }else {
       self.db.collection("Favorites").document().delete() { err in
            if let err = err {
                print("Error removing document: \(err)")
             }
       }
     }
}

【讨论】:

  • 感谢您的回答,但是每次单击按钮时它仍然会添加一个新文档,如果该文档存在,我该如何删除它。因此,例如用户在添加文档后单击,然后再次单击它会被删除。
  • 尝试在“self.isExist = true”下添加“break”
【解决方案2】:
   first, check if there is an existing document available if no then only inser
            func getExistingDocument() {
                //Get specific document from current user
                let docRef = Firestore.firestore().collection("users").document(Auth.auth().currentUser?.uid ?? "")
        
                // Get data
                docRef.getDocument { (document, error) in
                    if let document = document, document.exists {
                        let dataDescription = document.data()
                        print(dataDescription?["firstname"])
                    } else {
     

                   print("Document does not exist")
                       //here you can perorm insert new document
                    }
                }
            }

【讨论】:

  • 感谢您的回答,但是,如果存在,我将如何删除现有文档?
  • 您也在此处搜索用户集合。如果有商店 ID 和用户 ID,我需要在收藏夹集合中搜索,如果它们存在,我删除此文档,否则我将添加一个新文档
  • 使用 document.reference.delete() 方法,如果你想删除现有文件,你可以删除它,但我建议你更新现有文件而不是删除 :)
  • 您可以根据您的代码更改表名。给你我项目中的工作代码:)
  • 问题是,你上面的代码接受一个文档参数。那不是我想要做的。你的方式对我不起作用。不过还是谢谢你
猜你喜欢
  • 2021-07-24
  • 1970-01-01
  • 1970-01-01
  • 2018-05-08
  • 1970-01-01
  • 2020-12-11
  • 2020-09-01
  • 2018-06-18
  • 2021-10-16
相关资源
最近更新 更多