0
votes

I am trying to make a firestore structure similar to the following:

collection (userID) --> document (courseID) --> subcollection (lectureID) --> Q&A arrays

where the userID, courseID, and lectureID are all randomly generated values by firestore. Using authentication via firebase allows for the userID to be randomly generated, and the code below works well to create a course with a random courseID:

firestore.collection(authorId).add({

     (...)

However, I'm running into issues trying to create a subcollection with a random Id. At first I was trying to do something such as:

firestore.collection(authorID).doc(courseID).add({

     (...)

but the .add() apparently doesn't work for subcollections. Is there another function I can use that will allow me to create a subcollection?

1

1 Answers

1
votes

If you want add a document to a subcollection, you need to build a reference to it, using a name that you decide ahead of time, then add() the document using that reference.

firestore
    .collection(authorID)
    .doc(courseID)
    .collection("name-of-your-subcollection")
    .add({ ...})

I strongly suggest not using randomized names for subcollections, because you will have a very hard time finding and querying them later.