0

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

2
  • What is the programming language you're using? Please also edit your question and add your database structure as a screenshot. Commented Jun 22, 2022 at 15:01
  • @AlexMamo I've added the firestore structure and I am using Javascript Commented Jun 22, 2022 at 17:41

1 Answer 1

2

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().

Sign up to request clarification or add additional context in comments.

2 Comments

Exactly what I needed, Though I have one question, How can I delete an object. Cause I see you've used an arrayRemove function and basically we have pass the exact element for to remove that element. Thanks.
@random_18 in case of array of objects you need to know the exact object. If you only know value of a single property then you cannot use arrayRemove(). You will then have to read the document first and update manually as explained here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.