2
votes

Please help me solve this, I would like to update the fields using dot notation, using set() but each time I run with the below implementation. I have the fields added to firestore as e.g studentInfo.0.course.0.courseId instead of updating the already existing ones.

Json sample as it sits in firestore

    "schoolId": "school123",
    "studentInfo": [
        {
            "studentId": "studentI23",
            "regDate": "2020-04-18",
            "course": [
                {
                    "courseId": "cs123",
                    "regDate": "2020-05-28",
                    "status": "COMPLETED"
                }
            ]
        
        }
    ],
    "registered":"yes"
}

Code logic

const query = firestore.collection('users').where('registered', '==', 'yes')
const students = await query.get()
 students.forEach(student => {
    firestore.doc(student.ref.path).set({
        'studentInfo.0.studentId': '345','studentInfo.0.course.0.courseId': '555'
      }, { merge: true })
 }) 

On the docs https://firebase.google.com/docs/firestore/manage-data/add-data#update_fields_in_nested_objects I can only find updating nested objects but not nested array objects.

1

1 Answers

4
votes

It is indeed not possible to update a single element in an array using dot notation, or otherwise. To update an array you'll need to:

  1. Read the document
  2. Get the current value of the array from it
  3. Determine the new array contents
  4. Write the entire updated array back to the database.

The only alternative array operations are array-union and array-remove, which add and remove unique elements to/from the array - essentially treating it as a mathematical set. But since you are looking to update an existing element, these operations are of no use here.

Also see: