Home > Mobile >  Firebase: Removing an Object from an Array
Firebase: Removing an Object from an Array

Time:12-07

i'm trying to delete an specific object from an array in Firestore via SwiftUI. The following function deletes the whole watchlist. What am I missing?

func removeFromWatchlist() {
        
    if let uid = Auth.auth().currentUser?.uid {
        let docRef = db.collection("user").document(uid)     // company.symbol = "AAPL"
        docRef.updateData(["watchlist": FieldValue.arrayRemove([company.symbol])]) { error in
            if error == nil {
                print("Successful deleted array")
            }
        }
    }
}

And here is my Firestore structure: Firestore structure

CodePudding user response:

To remove an item from an array with FieldValue.arrayRemove you must specify the exact, complete data that is stored in the array.

Assuming your company.symbol is AAPL, the call FieldValue.arrayRemove([company.symbol] removes that exact string from the array - not the AAPL key that you have with an object under it.

You'll have to read the entire array from the document into you application code, remove it there, and then write the entire modified array back to the document.

  • Related