Home > Mobile >  How to append nested data in firestore
How to append nested data in firestore

Time:03-09

{
   "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
                    ]
                ])

CodePudding user response:

If you want to store the vote count for a number of keys:

  1. Don't store the counts as an array, but store them in a map field.
  2. 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)

CodePudding user response:

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")
    })
}
  • Related