fireclint
fireclint

Reputation: 65

Firebase React: Remove Item (Map) from array in firestore

I'm trying to remove a map item from an array in firebase. From what I understand with firebase - you are unable to delete the item based on the index. Should I structure this a different way or is there an easier way to remove a specific object from the array? Thank you

Error: 'No document to update: '

enter image description here

  const listingRef = doc(db, 'users', 'savedListings');

  const deleteListing = async () => {
    try {
      await updateDoc(listingRef, {
        savedListings: deleteField()
      });
    } catch (e) {
      console.log(e.message);
    }
  };```

Upvotes: 2

Views: 1026

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50850

The doc() takes path to a document that should be users/[email protected] in this case. While you can use arrayRemove() to remove elements from an array field you cannot delete an object from an array unless you know the exact value that object including all the fields.

const listingRef = doc(db, 'users', 'USER_EMAIL'); // USER_EMAIL is document ID

const deleteListing = async () => {
  try {
    await updateDoc(listingRef, {
      savedListings: arrayRemove("THAT_OBJECT")
    });
  } catch (e) {
    console.log(e.message);
  }
};

If you don't have that exact object, then you'll have to read the document, manually remove the element from array and update the document back.

Upvotes: 1

Related Questions