Daniel Corona
Daniel Corona

Reputation: 1222

Delete a array element from a Firestore database

I'm trying to delete an element from an array in a Firestore document. However, none of the approaches I tried had worked so far. My last attempt was like this:

  const ref = firestore().collection('events').doc(extraid);
  ref.get().then(document => {
    const thing = document.data();
    const rejected = thing.rejected || [];
    const interested = thing.interested || [];

    const fieldIndex = interested.findIndex(obj => obj.interestedId === sender);
    const fieldToDelete = interested[fieldIndex];
    firebase.firestore.FieldValue(fieldToDelete);
    firebase.firestore.FieldValue.delete(fieldToDelete);
  });

How can I delete an element from an array in a Firestore document?

Upvotes: 0

Views: 160

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317372

You will have to update() the modified array field back to the document as suggested by the documentation. Calling FieldValue.delete() isn't enough - that just creates a FieldValue token that you can pass to update() to make the change. It will look something like this:

ref.update('interested', FieldValue.delete(fieldToDelete))

Upvotes: 1

Related Questions