0

I'm creating a Firebase project and I have a collection with a nested collection. I have tried to perform CRUD operations in the parent collection but I have no idea how to get the document data from the nested array.

Here is what my firestore database looks like: enter image description here

and here is the code that I wrote for reading and creating a document in the parent child:

    const addEntry = () => {
    try {
        const docRef = firestore.addDoc(firestore.collection(db, "quiz"), {
            question: "How many sides are equal in a scalene triangle?",
            question_no: 1,
        });
        console.log("Document written with ID: ", docRef.id);
    } catch (e) {
        console.error("Error adding document: ", e);
    }
};
const getData = () => {
    firestore
        .getDocs(firestore.collection(db, "quiz"))
        .then((querySnapshot) => {
            querySnapshot.forEach((doc) => {
                console.log(`${doc.id} => ${doc.data()}`);
            });
        });
};

How can I get the data from the sub-collection or the nested collection.

Dharmaraj
  • 29,469
  • 5
  • 26
  • 55
zain
  • 316
  • 2
  • 11
  • You can keep adding path segments in `collection()` so to get documents from options sub-collection you can try: `.getDocs(firestore.collection(db, "quiz", "QUIZ_ID", "options"))` Do checkout the linked answer. If you are querying options for multiple quizzes then this might be helpful too [async-await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – Dharmaraj Feb 26 '22 at 19:11

0 Answers0