Home > OS >  Firestore update value in map of maps
Firestore update value in map of maps

Time:12-04

I try to add values to a map of maps using cloud functions and firestore. The maps might not exist and there can not be an entry with the personID key.

Right now I am accomplishing this by the following code:

if (!userData!.requests){
    userData["requests"] = {};
}
if (!userData!.requests.outgoing){
    userData!.requests["outgoing"] = {};
}

userData!.requests.outgoing[`${personID}`] = data;
t.update(usersRef, userData!);

Is there an easier way to do this? And is there a way without the need to read the data first?

CodePudding user response:

If you only have maps, you should be able to use dot notation to write/update a nested field:

usersRef.update({
    ["requests.outgoing." personID]: data
})

If you have an array anywhere in the path to the data, this won't work though. You can only add/remove items in an array without reading them, updating any existing array element requires a read-update-write cycle.

  • Related