Search code examples
firebasegoogle-cloud-firestorefirebase-security

firestore delete a document's subcollection not working


Seriously stumped on this one. I am trying to delete a nested record inside of the collection "kids".

"todaysEvents" is a map (inside of the kid's collection) and I am targeting the deletion of one of the key/value pairs (the event.id). I have given all permissions and when I run it, it returns that the document was successfully deleted yet it actually has not been deleted as i can still see it in the DB. Is there something special with maps that I need to do before deleting? I feel like this should work smoothly...

FIRESTORE.db
    .collection("kids")
    .doc(event.kidId)
    .collection("todaysEvents")
    .doc(event.id)
    .delete()
    .then(data => {
      console.log("Document successfully deleted!", data);
    })
    .catch(error => {
      console.error("Error removing document: ", error);
    });

enter image description here


Solution

  • Firestore is a Document Store Database. The operations available to you are to find/read, create, update and delete individual and ENTIRE documents (think: JSON objects) at a time.

    There is no API to delete just a field within an existing document. Rather, you need to read the document (the JSON object), modify the object (e.g. delete an element out of the document), and then write the document back to Firestore.

    So in your example you would do something like (pseudo-code below):

    const removeEventId = async (kidId, todayEventsId) => {
      try {
        // fetch the "kids" document
        let docRef = FIRESTORE.db.collection("kids").doc(kidId);
        let docSnap = await docRef.get();
        let docData = docSnap.data();
    
        // remove the element that we no longer want in the document
        delete docData.todaysEvents[todaysEventId];
    
        // update the document in Firestore
        await docRef.update(docData);
        console.log(`Document updated with ${todaysEventId} removed!`, docData);
      } catch (ex) {
          console.error(`EXCEPTION while removing ${todaysEventId}:`, ex);
      }
    }