0

So I am trying to delete the field Notes[1], selectedNote has a value of the selected array I need to delete.

window.addEventListener("load", function load(event) {
  document.getElementById("deleteNotes").onclick = function() {
    console.log("you did click atleast");
    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        let user = firebase.auth().currentUser;
        let userInfo = db.collection("Users").doc(user.uid);
        userInfo.get().then(function(doc) {
          if (doc.exists) {
            let selectedNote = document.getElementById("noteSelect")
              .selectedIndex;
            console.log(selectedNote);
            var cityRef = db.collection("Users").doc(user.uid);
            cityRef.update({
             Notes: FieldValue.delete().arrayRemove(selectedNote)
            });
          }
        });
      }
    });
  };
});

So I am trying to use this

 cityRef.update({
             Notes: FieldValue.delete().arrayRemove(selectedNote)
            });

to delete the selectedNote which is the array 1 for example inside of Notes. I don't want the entire Notes field deleted but just the selected array inside the Notes field. For some reason I am struggling to get it working. Any help would be appreciated <3

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
CodingIsFun33
  • 433
  • 3
  • 14

1 Answers1

0

Firebase arrays doesn't use a indexes for their arrays, instead they require the value of the array entry. this does mean you can't get away with duplicated data.

you will have to fetch the array "Notes" first and return its value from its index Although, I have heard that the arrays can come back out of order because they don't rely on an index.

change this line;

Notes: FieldValue.delete().arrayRemove(selectedNote)

to this;

Notes: FieldValue.delete().arrayRemove(doc.data().Notes[selectedNote])

I would recommend you pull the value of the array from a stored variable locally to ensure the values match pre and post edit.

DIGI Byte
  • 4,225
  • 1
  • 12
  • 20