I'm trying to create a 2D array in firestore, which can be updated using array union, but am struggling to work out how to do this. I can do it in a 1D array easily with this:
db.collection('subjects').doc('exampleDoc').update({ units: firestore.FieldValue.arrayUnion({ "name": "Example Unit", "id": "123456787654323456765" }) });
Which produced something like this:
name: 'Example Subject',
units: [
{
id: '123456787654323456765',
name: 'Example Unit'
}
]
But how can I do this with a 2D array with the data below as an example document?
name: 'Example Subject',
units: [
{
id: '123456787654323456765',
name: 'Example Unit',
subunits: [
{
id: '234568765434567',
name: 'Example Subunit'
}
]
}
]
You won't be able to do this with a simple arrayUnion. That's because Firestore does not support syntax to locate a specific indexed array element like it can with named, nested fields.
What you'll have to do is read the document, modify the field in memory to make it look the way you want, then update that entire field back to the document.