'How to append nested data in firestore
{
"userID": "MyID123"
"voteInfo": {
"docId1": 1
"docId2": 1
"docId3": 2
....
}
}
I would like to record which number the user voted for each two-point questionnaire. At first, only the user ID exists in the 'users' document, and I want to add data whenever I update it.
My code that is not working is as follows.
let userID = "MyID123"
let docID = "Ffeji341Fje3"
db.collection("users").document(userID).updateData([
"voteInfo": [
docID: 1
]
])
Solution 1:[1]
If you want to store the vote count for a number of keys:
- Don't store the counts as an array, but store them in a map field.
- Use the atomic increment operator to increase the vote count.
let key = "voteInfo."+docId
let update = [String:Any]
update[key] = FieldValue.increment(Int64(1))
db.collection("users").document(userID).updateData(update)
Solution 2:[2]
You can do this pretty easily through dot notation.
Given this Firestore structure
user_votes
uid_0
voteInfo //a map
docId1: 1
docId2: 1
docId3: 2
here's a function to append docId4: 1 to the existing docs
func addDoc() {
let collection = db.collection("user_votes").document("uid_0")
let newData = [
"voteInfo.docId4": 1
]
doc.updateData(newData, completion: { error in
if let err = error {
print(err.localizedDescription)
return
}
print("success")
})
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Frank van Puffelen |
| Solution 2 | Jay |
