简体   繁体   中英

Can you append a string to a Firebase array with swift

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)
            }
        }
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM