'How To Remove and Add Double Nested Elements in Firestore Array

I have a nested Codable Object In another object array in another object. I don't see how I can use FieldValue.arrayRemove[element]. Anyone know to do this? Thanks. I am trying to make it so that I can remove a cardField element in the LevelCard element in the job array.

Here is my code

    struct Job: Identifiable, Codable {
var id: String? = UUID().uuidString
var uid: String = ""

var title: String = ""
var description: String = ""
var images: [ImagesForJob] = []
var levelCards: [LevelCard] = []
var tags: [Tag] = []}

struct LevelCard: Identifiable, Codable {
var id = UUID().uuidString
var name: String = ""
var color: String = "A7D0FF"
var fields: [CardField] = []}

struct CardField: Identifiable, Codable {
var id = UUID().uuidString
var name: String = ""
var value: String = ""
var type: FieldType = .Text}

    func removeExistingCard(id: String, card: LevelCard) {
    
    var data: [String: Any] = ["":""]
    do {
        let encoder = JSONEncoder()
        let jsonData = try! encoder.encode(card)
        data = try JSONSerialization.jsonObject(with: jsonData, options: []) as! [String : Any]

    } catch {
        print("Error encoding account info\(error.localizedDescription)")
    }
    
    db
        .collection("listings")
        .document(id)
        .updateData(["levelCards": FieldValue.arrayRemove([data])]) {err in
            if let err = err {
                withAnimation {
                    self.errMsg = "Failed to delete card: \(err.localizedDescription)"
                    self.showErrMsg = true
                }
                return
            }
            self.getUsrLstngs()
        }
}

func removeExistingField(id: String, field: CardField) {
    
    var data: [String: Any] = ["":""]
    do {
        let encoder = JSONEncoder()
        let jsonData = try! encoder.encode(field)
        data = try JSONSerialization.jsonObject(with: jsonData, options: []) as! [String : Any]

    } catch {
        print("Error encoding account info\(error.localizedDescription)")
    }
    
    db
        .collection("listings")
        .document(id)
        .updateData(["levelCards": FieldValue.arrayRemove([data])]) {err in
            if let err = err {
                withAnimation {
                    self.errMsg = "Failed to delete card: \(err.localizedDescription)"
                    self.showErrMsg = true
                }
                return
            }
            self.getUsrLstngs()
        }
}

Also, Bonus, Does anyone know how to ignore the "id" variable when encoding all of my objects to Firestore? Thanks again.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source