gavisio
gavisio

Reputation: 79

Firebase: Removing an Object from an Array

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

Upvotes: 0

Views: 579

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

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.

Upvotes: 1

Related Questions