How to Use arrayUnion in Firestore for Array Updates
Use
arrayUnion in Firestore to add elements to an array field without duplicating existing values. It updates the document by appending only new unique items to the array.Syntax
The arrayUnion function is used inside an update or set operation to add elements to an array field. It takes one or more values as arguments and adds them only if they are not already present.
fieldName: The name of the array field to update.arrayUnion(value1, value2, ...): Adds unique values to the array.
javascript
import { getFirestore, doc, updateDoc, arrayUnion } from 'firebase/firestore'; const db = getFirestore(); const docRef = doc(db, 'collectionName', 'docId'); await updateDoc(docRef, { fieldName: arrayUnion(value1, value2) });
Example
This example shows how to add new tags to a Firestore document's tags array field without duplicating existing tags.
javascript
import { initializeApp } from 'firebase/app'; import { getFirestore, doc, updateDoc, arrayUnion } from 'firebase/firestore'; const firebaseConfig = { // your config here }; const app = initializeApp(firebaseConfig); const db = getFirestore(app); const docRef = doc(db, 'posts', 'post1'); async function addTags() { await updateDoc(docRef, { tags: arrayUnion('firebase', 'cloud') }); console.log('Tags updated with arrayUnion'); } addTags();
Output
Tags updated with arrayUnion
Common Pitfalls
Common mistakes when using arrayUnion include:
- Using it on a field that is not an array, which causes errors.
- Expecting it to remove duplicates from the entire array; it only prevents adding duplicates of the new values.
- Not awaiting the update operation, leading to race conditions.
Always ensure the field exists as an array or is created as one.
javascript
import { updateDoc, arrayUnion } from 'firebase/firestore'; // Wrong: field is a string, not an array await updateDoc(docRef, { title: arrayUnion('new') // Error: title is not an array }); // Right: update an array field await updateDoc(docRef, { tags: arrayUnion('new') });
Quick Reference
- arrayUnion(...elements): Adds unique elements to an array field.
- Use inside
updateDocorsetDocwith merge. - Does not remove existing duplicates in the array.
- Works only on array fields or creates them if missing.
Key Takeaways
Use arrayUnion to add unique items to Firestore array fields without duplicates.
arrayUnion only adds new values; it does not remove duplicates already in the array.
Always await update operations to ensure data consistency.
Ensure the target field is an array or will be created as one.
Use arrayUnion inside updateDoc or setDoc with merge to modify arrays safely.