Firestore: How to write to multiple sub-collections of one collection to firestore using Dart

Viewed 445

As part of a project we are using Firestore and we have a recipe collection that in it there are three sub-collections: ingredients, method and comments.

I can write data to one sub-collection but I can't seem to work out how to write the second sub-collection to the same document. At the moment it generates two documents. One for ingredients and another for method.

We are generating unique IDs generated from firestore and I understand that I need to use that doc ID, but I can't work out how to do it. Looking online, I can only see how to write to one sub-collection and not two.

    FirebaseFirestore.instance.collection('recipe').add({}).then((response) {
      print(response.id);
      FirebaseFirestore.instance
          .collection("recipe")
          .doc(response.id)
          .collection("ingredients")
          .add({
        "allergies": allergies,
        "category": categoryValue,
        "description": descriptionController.text,
        "image": "testing",
        "ingredients": ingredients,
        "prepTime": prepTime,
        "protein": proteins,
        "servings": servingsController.text,
        "title": recipeNameController.text
      }).then((response) {
      print(response.id);
      FirebaseFirestore.instance
          .collection("recipe")
          .doc(response.id)
          .collection("method")
          .add({
        "method": methodSteps
      });
    });
    });
1 Answers

It should be easier with async/await:

var recipeDocRef = await FirebaseFirestore.instance.collection('recipe').add({...});

await recipeDocRef.collection("ingredients").add({...});
await recipeDocRef.collection("method").add({...});
await recipeDocRef.collection("comments").add({...});

recipeDocRef is a DocumentReference, so you just need to call the collection method in order to declare subcollections of this document (i.e. CollectionReferences).

Related