cjmc
cjmc

Reputation: 101

Trying to call a document id from a sub-collection in firestore

I'm trying to run a delete function that should be fairly straight forward but i'm not getting it.

I referenced the document within the sub-collection but it doesn't seemed to be referenced correctly. When I hard code the answer documents id it performs the function but when I try to reference it doesn't work.

I have the document information stored in an array but I need to cycle through the array to find the id that matches the post. I'm having trouble grabbing the reference from 'getAnswer' once it is stored.

Here is the code:

    const [getAnswer, setGetAnswer] = useState([]);

    useEffect(() => {
    let mounted = true;

    db.collection("questions")
      .doc(questionId)
      .collection("answer")
      .orderBy("timestamp", "desc")
      .onSnapshot((snapshot) => {
        if (mounted) {
          setGetAnswer(
            snapshot.docs.map((doc) => ({
              id: doc.id,
              answers: doc.data(),
            }))
          );
        }
      });

    return () => (mounted = false);
  }, []);

  const handleDeletePost = (e) => {
    if (user) {
      db.collection("questions")
        .doc(questionId)
        .collection("answer")
        .doc(getAnswer.id)
        .delete();
    }
  };

  const answerMenuId = "primary-answer-account-menu";
  const answerRenderMenu = (
    <Menu
      anchorEl={anchorEl}
      anchorOrigin={{ vertical: "top", horizontal: "right" }}
      id={answerMenuId}
      keepMounted
      transformOrigin={{ vertical: "top", horizontal: "right" }}
      open={isMenuOpen}
      onClose={handleMenuClose}
    >
      <MenuItem onClick={handleMenuClose}>Edit</MenuItem>
      <MenuItem onClick={handleMenuClose} onClick={handleDeletePost}>
        Delete
      </MenuItem>
    </Menu>
  );

For a bit more context I would like to delete an answer document based on the id of the document. Here is a screenshot of the database:

enter image description here

Upvotes: 0

Views: 646

Answers (2)

LeadDreamer
LeadDreamer

Reputation: 3499

Your getAnswer is an array, and it is NOT indexed by id. It is an array of objects, each of which has properties id and answers, in the order the query returns documents by timestamps.

getAnswer.id is meaningless in this context, and it's completely unclear what user, questionId and id even are in the context you show.

what event are you processing? how do you know which answer is indicated by the event? is it a button? select? checkbox? radio button?

Also note: each DocumentSnapshot in the QuerySnapshot INCLUDES doc.ref.path, which you could pass directly for db.doc(refPath).delete() - no need to construct the .collection().doc().collection() etc etc.

I use a wrapper package for FirebaseFirestore that always includes the doc.ref.path as refPath in my Record objects for exactly this reason - also, you can parse it to find parent documents, etc

Upvotes: 1

Frank van Puffelen
Frank van Puffelen

Reputation: 598623

Assuming that answerId is a variable that is holding the document ID of the answer to delete, you're looking for:

const answersDocumentRef = db.doc("answer/"+answerId);

Or alternatively:

const answersDocumentRef = db.doc(`answer/${answerId}`);

Or (without the answersDocumentRef):

db.collection("questions")
    .doc(questionId)
    .collection("answer")
    .doc(answerId)
    .delete();

Or alternatively for that:

db.doc(`questions/${questionId}/answer/${answerId}`).delete();

Upvotes: 1

Related Questions