jcodey
jcodey

Reputation: 49

How To Delete An Object inside a Field in Firestore

Self taught coder here. I'm trying to make a function that would delete a specific object inside a field within firebase. It's for something similar to a to-do app. Inside my firebase structure, here is what I'm trying to delete (either object 0 or 1 as pointed out with red arrows:

enter image description here

My function looks like this but I don't think I can use bracket notation, and I haven't had any luck with dot notation either.

  const deleteLabel = async (id) => {
    await updateDoc(labelCollectionRef, currentUser.uid, {
      labels: arrayRemove(1),
    });
    console.log("label deleted!");
  };

I've had a few errors, the main one right now being this:

Uncaught (in promise) FirebaseError: Expected type 'ba', but it was: a custom va object

Upvotes: 0

Views: 216

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

The deleteField operator can only be applied to a complete field, like for example the entire labels array. It cannot be used to remove a single item from that array.

To remove an item from the field, you can use the arrayRemove operator, passing in the entire content of the item in the array as the value:

updateDoc(doc(db, "users", currentUser.uid), {
  labels: arrayRemove({id: "nhl"}),
});

Upvotes: 2

Related Questions