Memphis Meng
Memphis Meng

Reputation: 1681

Update a field of a document in Firestore database

I am an iOS app developer. Right now, I need my app to update his/her scores in the database (Firestore) when a user tabs a button.

I only know that it is possible to add new documents to the database according to the official doc: https://firebase.google.com/docs/firestore/quickstart#swift. But can I simply update one key-value pair within a document at a time?

For example, I have to add 10 points to the user with ID: 1234 if he/she clicks the correct button. So first of all, I need to read the data according to the unique ID, and catch his/her current points. Then put back the points plus 10.

It looks like Firestorage only allows users to upload an entire document once a time.

Swift code snippet is appreciated!

Upvotes: 0

Views: 753

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600036

You can update a single or multiple fields in a document with the updateData call.

To atomically increment a numeric value can you can use the FieldValue.increment operation. From that last link comes this example:

washingtonRef.updateData([
    "population": FieldValue.increment(Int64(50))
])

This code increments the population field in the document by 50, and leave other fields in the document unmodified.

Upvotes: 1

Related Questions