1

I am keeping track of whether or not a user likes a restaurant in firebase but I am currently using a string to do this. I know its possible to update an array in Firebase but from what I have read in order to do this you need to rewrite the entire array every time you want to add a new element. Is there any way to just append a string to the end of the array? And if that's not possible does anyone know a better alternative then just using a string?

This is what I'm using right now:

var likedBarsGlobal: [String] = [] {
    didSet {
        var lb = ""
        for i in 1...likedBarsGlobal.count - 1 {
            if(i == likedBarsGlobal.count - 1){
                lb += "\(likedBarsGlobal[i])"
            } else {
                lb += "\(likedBarsGlobal[i]), "
            }
        }

        db.collection("users").document(userId).updateData(["likedBars": lb ]) { (error) in
            if error != nil {
                print(error)
            }
        }
    }
}

1 Answer 1

5

Firestore has a special documented operation to append a single item to the end of an array using FieldValue.arrayUnion():

let washingtonRef = db.collection("cities").document("DC")

// Atomically add a new region to the "regions" array field.
washingtonRef.updateData([
    "regions": FieldValue.arrayUnion(["greater_virginia"])
])

If you want make any changes to an array other than add or remove a single item, you will have to read the array, modify it, then write it back.

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

1 Comment

this should have more than 3 up votes. i didn't find this answer anywhere else and it answers so nicely such a needed question.

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.