简体   繁体   中英

How to delete a document from firestore if it exists in swift?

i am trying to validate if a user has already liked a store before or not. if he did not it would add the data to the firestore collection, otherwise if he clicks again it would delete it.

right now everytime i click the button it adds a new document, i am not able to figure out how to delete the existing document if he clicks again.

@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()
                  }
                    }
                }
                }
            }
    }

any help on this? thank you

You are sending nested requests to Firebase (First: getDocuments , Second: addDocument or delete ). Change your code to :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM