1

The Firestore database has the following field structure

images: {day: ['url1', 'url2', 'url3,] night: ['url1']}

First I would like to be able to append a value to the arrays. Did try the following:

await updateDoc(doc(firestore, FIRSTORE_COLLECTIONS.IMAGES, id), {
        [folder]: {
          [key]: arrayUnion(fileUrl)
        }

It went to the right images: path but unfortunately this just created a new array with one value and removed the ones that where there.

Secondly. If I also like to be able to create a new array in the same path with a key that does not exist can this be done and how could that be solved with this setup any ideas?

dependencies: "firebase": "^9.1.1", "react": "^17.0.2"

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Patrik Rikama-Hinnenberg
  • 1,362
  • 1
  • 16
  • 27
  • Does this answer your question? [Firestore Update single item in an array field](https://stackoverflow.com/questions/52187985/firestore-update-single-item-in-an-array-field) – Donnald Cucharo Jan 05 '22 at 08:06
  • @Dondi So if I understand correctly and as also said in the docs and that answer you can add a new element to the array ("arrayUnion") or remove an element ("arrayRemove"). – Patrik Rikama-Hinnenberg Jan 05 '22 at 10:15
  • I mean we should be able to append on an array a new value ? – Patrik Rikama-Hinnenberg Jan 05 '22 at 10:17
  • Further I can see the firebase lite is used: `import { arrayUnion } from 'firebase/firestore/lite';` but that should not be the problem? – Patrik Rikama-Hinnenberg Jan 05 '22 at 10:22
  • The docs v9 also says it should work: arrayUnion(elements) - Returns a special value that can be used with setDoc() or updateDoc() that tells the server to union the given elements with any array value that already exists on the server. Each specified element that doesn't already exist in the array will be added to the end. If the field being modified is not already an array it will be overwritten with an array containing exactly the specified elements. https://firebase.google.com/docs/reference/js/firestore_lite.md#@firebase/firestore/lite – Patrik Rikama-Hinnenberg Jan 05 '22 at 13:41
  • Last sentence there if the field being modified is not already an array it will be overwritten.. hmm just like it would be overwritten in my case. – Patrik Rikama-Hinnenberg Jan 05 '22 at 13:43

1 Answers1

1

This is what solved it:

 await updateDoc(ref, {
        [`${folder}.${key}`]: arrayUnion(fileUrl)
      });

Proper path where the arrayUnion methods is implemented. It also creates a new array if key does not exists, which is nice.

Patrik Rikama-Hinnenberg
  • 1,362
  • 1
  • 16
  • 27