Home > Mobile >  adding items to a specific subcollection in firebase with flutter
adding items to a specific subcollection in firebase with flutter

Time:10-06

im trying to add more elements to a subcollection in firebase.

here i made a course collection then a subcollection (sections). i want to add new elements(students) to sections. in order to do that i need to put the path of the subsection from the firebase but this is hardcode and i want it to be flexible for any section. all sections have a unique number(secID). is there a way that i can look for a specific section and get the path for it to put it in .doc("") ?

this is the code im working with :

    Future<void> courseSetup(String courseName, String cHours) async {
  CollectionReference c = FirebaseFirestore.instance.collection('Courses').doc().collection("Sections");
  FirebaseAuth auth = FirebaseAuth.instance;
  c.add({'Course name': courseName, 'Course hours': cHours});
  return;
}

the attributes aren't showing the nested collections this is my firebase :

enter image description here im struggling with nested collection in firebase please help

CodePudding user response:

Calling doc() without an argument always generates a new unique document ID. So in this call:

CollectionReference c = FirebaseFirestore.instance.collection('Courses').doc().collection("Sections");

You end up with the Sections subcollection of a new document, not of the existing course that you want to update. You will need to know the ID of the course that you want to update, typically by keeping that in your code when you read the courses from the database.

Once you do, you can add the section to that could with:

CollectionReference c = FirebaseFirestore.instance.collection('Courses').doc("courseID").collection("Sections");
  • Related