0

please see my firestore structure enter image description here

I want to set my document title as sequential. my structure as [Table] - Drinks - ["Drink (sequence)"] my first issues : my document title does follow sequence, like "Drink 1" and "Drink 2" etc however when I add new drinks to Another Table - the new document starting from Drink 3 rather than drink 1.

my second issues : if there were "drink 1" and "drink 2 documents", if I delete them then recreate the document title start from drink 2. I don't know what's wrong please help me .

my codes for doing this is

    var drinkCount : Int = 1
     func generateDrinkTitle(table: String,complete:@escaping() -> Void) {
        let docRef = db.collection("Active Table").document(table).collection("Drinks")
        
        docRef.getDocuments { querySnapshot, error in
            if let err = error {
                print("Error in getting: \(err.localizedDescription)")

            } else {
                self.drinkCount = 1
                for doc in querySnapshot!.documents {
                    self.drinkCount += 1
                }
            }
        }

        complete()
    } 

my whole code

class OrderViewModel : ObservableObject {
var drinkCount : Int = 1

    func saveDrinks(table : String) {
        var drinks : [[String : Any]] = []
        var drinkextra : [[String: Any]] = []
        for j in cartDrinks {
            for i in j.extra {
                drinkextra.append(["extra": i.extra,"price": i.price])
                drinks.append(["Name":j.name,
                               "Unit":j.unit ,
                               "Price":j.price,
                               "Extra": drinkextra
                              ])
                drinkextra.removeAll()
            }
        }
        db.collection("Active Table").document("Table \(table)").collection("Drinks").document("Drink \(self.drinkCount)").setData(["Drinks": drinks]){ error in
            if let error = error {
                print(error.localizedDescription)
                
            } else {
            }
        }
    }

    func generateDrinkTitle(table: String,complete:@escaping() -> Void) {
        let docRef = db.collection("Active Table").document(table).collection("Drinks")
        
        docRef.getDocuments { querySnapshot, error in
            if let err = error {
                print("Error in getting: \(err.localizedDescription)")

            } else {
                self.drinkCount = 1
                for doc in querySnapshot!.documents {
                    self.drinkCount += 1
                }
            }
        }

        complete()
    }

    func FireUpload(table: String){
        db.collection("Active Table").document("Table \(table)").setData(["Time" : Timestamp(date: Date())]) { error in
            if let error = error {
                print(error.localizedDescription)
                return
            }
        }
        if !mealDeal.mainCourse.isEmpty {
            self.SaveMealDeal(table: table)
        }
        if !cartDrinks.isEmpty {
            generateDrinkTitle(table: "Table \(table)") {
                self.saveDrinks(table: table)
                self.drinkCount = 1
            }
        }
        if !cartexpress.isEmpty {
            self.SaveAlacarte(table: table)
        }

    }
}
RJC
  • 1,224
  • 2
  • 12
Liangn1an
  • 33
  • 6
  • 1
    "I want to set my document title as sequential" Sequential document IDs are an anti-pattern in Firestore (and most NoSQL databases) and will affect the performance of your app. What your reason for wanting this? – Frank van Puffelen Nov 19 '21 at 00:48
  • Can you add your whole code for understand please? – Siddharth Patel Nov 19 '21 at 06:10
  • hi @FrankvanPuffelen, I want to set this so my staff can easily identity the latest drinks round they have added then they can choose to delete them or move them to other Table collection due to choose table incorrectly or customer cancel the order etc. – Liangn1an Nov 19 '21 at 10:46
  • @SiddharthPatel I have included whole in my post now. many thanks – Liangn1an Nov 19 '21 at 10:51
  • Any sequential data should be in a FIELD, not the document Id - you can query by the fields. The document IDs are mostly useful for keeping documents unique - they perform *almost* no function in actual use (emphasis "almost") – LeadDreamer Nov 19 '21 at 17:03
  • Do not use monotonically increasing [document IDs](https://cloud.google.com/firestore/docs/best-practices#document_ids), such sequential IDs can lead to hotspots that impact latency. Also, you can check this [related post](https://stackoverflow.com/a/53901549/16531380) for further explanation regarding the use of sequential id. – RJC Nov 22 '21 at 08:39

1 Answers1

1

I have accept the counter idea suggested in the comments; many thanks for helping me. Here is my code for the counter id:

docRef.addSnapshotListener { documentSnapshot, error in
            guard let document = documentSnapshot?.exists else {return}
            if document {
                
                self.db.collection("Active Table").document(table).getDocument { documentSnapshot, error in
                    if let document = documentSnapshot,((documentSnapshot?.exists) != nil) {
                        let dataDescription = document.data()
                        let Dcounter = dataDescription?["DrinkCounter"] as? Int ?? 0
                        let Acounter = dataDescription?["AlacarteCounter"] as? Int ?? 0
                        self.alacarteCounter = Acounter
                        self.drinkCount = Dcounter
                    }
                }
            } else {
                print("No document")
                self.alacarteCounter = 0
                self.drinkCount = 0
                self.db.collection("Active Table").document(table).setData(["DrinkCounter": 0 as Int,"AlacarteCounter": 0 as Int,"MealDealCounter": 0 as Int,"Time": Timestamp(date: Date())])
            }
        }
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Liangn1an
  • 33
  • 6