Force the Firestore array to merge with the value that's already a part of the array

Viewed 780

There is a method arrayUnion() that we use to add additional element to the existing array. When adding the value that already existed in the array, however, it's not going to merge, and it's just going to persist one element instead of two.

Example:
Existing array = [2]
ArrayUnion([2])...
Resultant array [2]


Example 2;
Existing array = [3];
ArrayUnion([2])...
Resultant Array = [3, 2];

How can I make it work so that the resultant array in the first example would be [2, 2]?

2 Answers

From the documentation for arrayUnion:

Returns a special value that can be used with set() or update() 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.

The arrayUnion operator ensures that each unique value exists at most once in the array. There is no way to add a duplicate value with arrayUnion.

If you want to add a duplicate value, you'll have to read the entire array, modify it on the client, and write it back.

I found a workaround because I was facing the same issue. I don't know how well this will translate in the long run, but what I did is to add a random decimal at the end of the number.

I was able to update the array with the same integer value

FieldValue.arrayUnion(`${value}.${rand}`)

I know it may not be a proper solution, but hopefully it is not much of an issue when querying the data from my App. I'll omit the decimals there.

Related