Update fields in nested objects in firestore documents without removing other nested objects?

Viewed 229

I am working on a flutter project where I use Firebase Firestore as my database. Currently, I am having trouble with a cloud function. This function should update a nested object in my database.

The structure looks like this:

{
"plannings" : {
    "0" : {
        "finalSchedule": null, 
        "teacherName": "----", 
        "endDate": "8-11-2020", 
        "learnerAvailabilities": {
            "3vLYq8Zlm6Z2KkGDbdu3rwQWMTd2": null, 
            "DTtN4j1fngfjZM3p8v5JVyc7hrn2": null, 
            "ekzj2Iy8JngtourPvHQyQAHJx563": null, 
            "Ss9QV7qFVvXBzTe3R6lmHkMBEWn1": null, 
            "tzEe2jhcr7hn1X1gu7c8BfuyO5a2": null, 
            "otlqIURWB5SZeChzhoaQOmNEi6m2": null,
        }, 
        "name": "----", 
        "id": "#5a066",
        }
    },
"Learners" : {},
"etc..." : {},
}

I want to be able to update the value of every 'learnerAvailability' (ID) individually. So I tried this:

school.update({
    [`plannings.${key}.learnerAvailabilities.${userUID}`]: newSchoolUserAvailabilityObject,
});

But when I do so, every ID, except for the one changed, is removed. And "finalSchedule", "teacherName", "endDate", "name", "id" are also gone. So I end up with something like this when I change the value of "3vLYq8Zlm6Z2KkGDbdu3rwQWMTd2":

{
"plannings" : {
    "0" : {
        "learnerAvailabilities": {
            "3vLYq8Zlm6Z2KkGDbdu3rwQWMTd2": (new value), 
        }, 
        }
    },
"Learners" : {},
"etc..." : {},
}

I also can't just replace the "plannings" object entirely every time, because that causes trouble when two updates (.update) are happening at (almost) the same time.

1 Answers

The problem is that the "plannings" field started out as an array, but then you updated it to be a map. Firestore doesn't provide a way to update array items by index. If you want to modify an array item, you have to read the entire document, modify the array in memory, then update the document with the new contents of the array.

Related