Reputation: 153
I want to update a field of an object that the object is in an array in the Firestore database with Swift 4. These two functions (arrayUnion() and arrayRemove() ) are not working for me.
Here my Database schema:
I want to update the "Status" field in The first array element.
Upvotes: 1
Views: 2688
Reputation: 35648
I believe the question is:
how can I update a specific field that's stored within a document in an array.
As long as you know the documentId to the document you want to update - here's the solution.
Assuming a structure similar to what's in the question
Friends (a collection)
0 (a document)
Name: "Simon"
Status: "Sent"
1
Name: "Garfunkle"
Status: "Unsent"
and say we want to change Garfunkle's status to Sent
I will include one function to read document 1, Garfunkle's and then a second fuction to update the Status to sent.
Read the document at index 1 and print it's fields - this function is just for testing to show the field's values before and after changing the status field.
func readFriendStatus() {
let docRef = self.db.collection("Friends").document("1")
docRef.getDocument(completion: { document, error in
if let document = document, document.exists {
let name = document.get("Name") ?? "no name"
let status = document.get("Status") ?? "no status"
print(name, status)
} else {
print("no document")
}
})
}
and the output
Garfunkle Unsent
then the code to update the Status field to Sent
func writeFriendStatus() {
let data = ["Status": "Sent"]
let docRef = self.db.collection("Friends").document("1")
docRef.setData(data, merge: true)
}
and the output
Garfunkle, Sent
Upvotes: 1
Reputation: 153
first of all I want to thanks to @Doug Stevenson for his kindly response. in my case, I must change the array of the objects to sub collections.
Upvotes: 1
Reputation: 317362
In a transaction, fetch the document, modify the field of the object as you see fit in memory on the client, then update that entire field back to the document.
Upvotes: 0