If your document contains an array field, you can use arrayUnion() and arrayRemove() to add and remove elements. arrayUnion() adds elements to an array but only elements not already present. arrayRemo
import { doc, updateDoc, arrayUnion, arrayRemove } from "firebase/firestore";
const washingtonRef = doc(db, "cities", "DC");
// Atomically add a new region to the "regions" array field.
await updateDoc(washingtonRef, {
regions: arrayUnion("greater_virginia")
});
// Atomically remove a region from the "regions" array field.
await updateDoc(washingtonRef, {
regions: arrayRemove("east_coast")
});
// ...
const washingtonRef = db.collection('cities').doc('DC');
// Atomically add a new region to the "regions" array field.
const unionRes = await washingtonRef.update({
regions: FieldValue.arrayUnion('greater_virginia')
});
// Atomically remove a region from the "regions" array field.
const removeRes = await washingtonRef.update({
regions: FieldValue.arrayRemove('east_coast')
});
// To add or remove multiple items, pass multiple arguments to arrayUnion/arrayRemove
const multipleUnionRes = await washingtonRef.update({
regions: FieldValue.arrayUnion('south_carolina', 'texas')
// Alternatively, you can use spread operator in ES6 syntax
// const newRegions = ['south_carolina', 'texas']
// regions: FieldValue.arrayUnion(...newRegions)
});