DEV Community

anastacioSalazar
anastacioSalazar

Posted on

How to update an array of objects in firebase Firestore?

If your document contains an array field, you can use arrayUnion(),arrayUnion() adds elements to an array but only elements not already present.

  /* 1.- Imports */
  import { getFirestore, doc,updateDoc,arrayUnion } from "firebase/firestore";
  import { app } from '../../Config';

  /*2.-Initialize the connection to the database.*/
  const db = getFirestore(app);
  /*3.-Update to be done.*/
    const updateArrayCompany={
    Company:arrayUnion({Id:1001, Name:"New NAme", Active:true}
      )
    }


    const UpdateCollection=(id,value) =>{
      /*4.-indicate the collection to update.*/
      const CollectionUpdate = doc(db, "Company", id);
      /*5 Execute the update to the collection. */
      updateDoc(CollectionUpdate,updateArrayCompany).then(()=>{
      alert("Ok")
      })
      .catch((error)=>{
          alert(error.message)
        })
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)