2

I am making an ordering app for customers to order their specific specs. When the user logs in they can go to a tab that contains a tableview with all their specs, once they click on a cell it will take them to a new view controller that will display more information on the spec. Once on this view controller they will have the ability to add x amount of pallets/rolls/etc of that item. I am able to add the spec to Firestore, but I cannot get it to an array in Firestore which I need. My goal is that on anther tab the user can view all the current specs they are trying to order until they hit submit. I am currently using the user.uid to get to that specific customers orders inside Firestore.

Code: @IBAction func addPallet(_ sender: Any) {

    // Get the current user
    let user = Auth.auth().currentUser
    if let user = user {
        _ = user.uid
    }
    
    if spec != nil {
        
        // Get the qty ordered for that spec
        let totalQty: Int? = Int(palletsToAddTextField.text!)
        let qty = spec!.palletCount * totalQty!
        
        let specToAdd = Spec(specNumber: spec!.specNumber,
                        specDescription: spec!.specDescription,
                        palletCount: spec!.palletCount,
                        palletsOrdered: qty)

        orderedArray.append(specToAdd)
        
        let specAdded: [String: Any] = [
            "SpecDesc": spec!.specDescription,
            "SpecNum": spec!.specNumber,
            "PalletCount": spec!.palletCount,
            "PalletsOrder": qty
        ]
        
        
        
        db.collection("orders").document(user?.uid ?? "error").setData(specAdded) { err in
            if let err = err {
                print("Error writing document: \(err)")
            } else {
                print("Document successfully written!")
            }
        }
        
    }
    
}

code for spec: struct Spec: Codable {

// Properties
var specNumber: String
var specDescription: String
var palletCount: Int
var palletsOrdered = 0

enum CodingKeys: String, CodingKey {
    case specNumber
    case specDescription
    case palletCount
    case palletsOrdered
}

}

I need something added like the below picture. The user will add x amount of pallets, then going to the next spec they want and add it to the array in Firestore as well.enter image description here

2
  • You must treat the spec field (in the database) like an array. And to append elements to an array in Firestore, you must either grab the array, unpack it, add your element to it, and update the document with the new array or use arrayUnion to append elements without first reading it. firebase.google.com/docs/firestore/manage-data/… Commented Sep 9, 2020 at 22:24
  • Arrays in Firestore work a little differently than what you're used to in iOS. For example, if you only use arrayUnion, the array will never contain duplicates (in this sense it operates like a set more than an array, which is useful). However, if you directly write an array with duplicates (without using arrayUnion), those duplicates will remain. Read this for a primer: firebase.googleblog.com/2018/08/… Commented Sep 9, 2020 at 22:26

1 Answer 1

1

Ok i guess i get what you want to do. Try:

db.collection("orders").document(userID).setData(["allMyData" : myArray])

"allMyData" will be the name of the field in which you want to save your array and myArray would be your array (specAdded). Thats what you are looking for?

If the document already exists you will want to use .updateData instead of .setData to keep all other fields that might already exist in that specific doc.

Kind regards

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, its close to what I need. I will update my question to show what exactly I need.
Your database structure seems a bit odd to me but that might have its reasons. Maybe you should use a deeper order. db.collection("orders").document("userID").collection("specs").document().setData(...) You can also use arrayUnion() or arrayRemove() but to make full use of firestore features i would advise to go for document and collections hiereachy instead. If my answers helped please give me up or hit the solved button.
I am open to changing the structure of my database. I have two collections(users and orders) one for the user and their spec, and another for their orders, but after writing this is I should probably include the orders inside the users under each user. My end game is each user has their own specs and can add multiple specs to an order, so essential ever time they add a spec with x pallets it appends to the array inside Firestore. I could also probably just have the spec# and qty ordered instead of the rest of the data.
By looking at your screenshot, to me it seems like "specs" should be a collection and "0" and "1" will be documents in that collection. If you want to stick to your arrays you can do so by forementionend array operators. Good luck hope that helped.
I actually originally had it setup that way, but was unable to get the data correctly and add them to my custom object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.