如果文档迅速存在,如何从Firestore中删除文档?

时间:2020-09-15 07:52:31

标签: ios swift google-cloud-firestore

我正在尝试验证用户是否已经 以前是否喜欢商店。如果他不这样做,则会将数据添加到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()
                  }
                    }
                }
                }
            }
    }

对此有任何帮助吗?谢谢

2 个答案:

答案 0 :(得分:0)

您正在向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)")
             }
       }
     }
}

答案 1 :(得分:0)

   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
                    }
                }
            }