Better Arrays in Cloud Firestore!

Arrays haven’t always been the best data structure for multi-user environments like Cloud Firestore. As Kato describes in the “Arrays are evil” section of his blog post, bad things can happen if you have multiple clients all trying to update or delete array elements at specific indexes. In the past, Cloud Firestore addressed these issues by limiting what you can do with arrays. That means that until now, you could really only “update” arrays by replacing the entire array (no appending or deleting!), and you couldn’t perform meaningful queries on arrays, either.

This was problematic for those of you who wanted to use arrays in simple cases like keeping a list of tags or keywords. Previously, we’ve recommended you try a workaround (some might say, a “hack”) of converting your arrays into maps like this:

Well, with our latest improvements to arrays, none of this is necessary! For starters, we’ve added the ability to query for elements within arrays using the new ”array-contains” feature. This means you can keep your elements as an array, and easily query for them without having to resort to the map hack.

Even better, you can query for items in arrays that aren’t strings, which was a problem with the previous “convert your array into a map” workaround.

You also have the ability to add or remove elements from an array. But in order to avoid some of the issues that can arise in a multi-user environment, you’ll be adding them with more of a set-like functionality. So rather than asking to delete an item at index 3, you would ask to remove, for example, all elements of the string ”sly” with the arrayRemove operator.

With the arrayUnion operator, you can append an element to an array, but only if it doesn’t exist in the array already.

Adding “clever” to our array doesn’t do anything, because it already exists.

](https://3.bp.blogspot.com/-PsftFg472bs/W2HH92t-0XI/AAAAAAAACVM/xweu_-CGpXgvgk2o81sFcYCvuXFIPN9jQCLcBGAs/s1600/AddTwoimage5.png)

But adding “fuzzy” adds a new element to the array!

These changes also come with some improvements to security rules as well. Now you can create security rules that allow queries based on whether or not a certain element exists inside of an array. So doing things like querying for a list of documents, but only allowing that query if the user is listed inside of the documents’ ”viewers” array is significantly easier than before.

This kind of query request is now possible in Cloud Firestore

All of these features should be available with the latest client SDKs, so make sure you update to the latest versions of your libraries, and start having fun with arrays! As always, if you have questions, you can join the Cloud Firestore Google discussion group, or use the google-cloud-firestore tag on Stack Overflow.