0

Is there an easy way to add a value to an array in Firestore that already exists? I know arrayUnion() will not add a value to the array if it already exists, and I have read older replies that the only way to do this is to read the entire document, and then completely re-write the array, but that is incredibly inefficient (and could get expensive). Is there not a better way to do this in Firebase?

For example, if my value for update already exists in my array, I still want it to add it to my array.

'unitsLog': FieldValue.arrayUnion([update])
Dennis Ashford
  • 872
  • 2
  • 7
  • 21

1 Answers1

0

The arrayUnion operator explicitly only adds items that don't exist in the array yet.

If you want to add duplicates, you'll have to:

  1. Read the document from the database.
  2. Update the array contents in your application code.
  3. Write the entire array back to the database.
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807