Home > database >  Delete an array element using Firebase 9
Delete an array element using Firebase 9

Time:06-23

I've a simple document in my Firestore collection.

{
  "posts": ["0", "1", "3"],
  "title": "Delete an array element"
}

I know how to delete an entire document using the auto generated Direbase doc id but I'm not sure how do I delete a specific element in an array, let's here I'd like to delete the 1.
And I don't want to use updateDoc for this to work.
Using Javascript for the integration.

Database structure

CodePudding user response:

The updateDoc() function is required to update a document. You can use arrayRemove() function to remove an element from the array.

import { doc, updateDoc, arrayUnion, arrayRemove } from "firebase/firestore";

const docRef = doc(db, "collection", "docId");

await updateDoc(docRef, {
    posts: arrayRemove("1") // removes "1" from the array 
});

Do note that if you have an array of objects then you must pass the entire object to be removed in arrayRemove().

  • Related