Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

Swift/FireStore - Appending/updating elements in an array

Ok, so this feature is semi-working:

API.FIRESTORE_DOCUMENT_USERID(userID: userID).updateData(["user_rating":FieldValue.arrayUnion([averageRating])])

As you can tell, I'm trying to update the user_rating field and pass in the average rating. However, since the average rating can be anywhere from 1-5, including decimals/doubles, there is a likelihood that the average rating will already exist i.e. 1.5, 2.5, 2.7 etc. However, I cannot seem too append the same value twice. If I change the rating, then sure I can append. As far as I'm aware, each entry in an array has it's own ID? Any way I can allow for duplicates?

Thank you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Found the solution, you must first read the existing data in the array, then append whatever data you wish then once again update the data, like so:

[YOUR_REFERENCE].getDocument { (querySnapshot, error) in
                if let error = error {
                    print(error.localizedDescription)
                } else {
                    var array:[THE_DATA_TYPE] = querySnapshot?.get("[FIELD_NAME]") as [THE_DATA_TYPE]
                    array.append([DATA_YOU_WISH_TO_APPEND])
                    querySnapshot?.reference.updateData(["[FIELD_NAME]" : array])
                }
            }

I've made it generic in the event anyone ever just wishes to copy and paste.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...