【问题标题】:Firestore: How to write to multiple sub-collections of one collection to firestore using DartFirestore:如何使用 Dart 将一个集合的多个子集合写入 Firestore
【发布时间】:2021-04-09 16:31:21
【问题描述】:

作为项目的一部分,我们正在使用 Firestore,我们有一个食谱集合,其中包含三个子集合:成分、方法和 cmets。

我可以将数据写入一个子集合,但我似乎不知道如何将第二个子集合写入同一个文档。目前它会生成两个文档。一个是成分,另一个是方法。

我们正在生成从 firestore 生成的唯一 ID,我知道我需要使用该文档 ID,但我不知道该怎么做。在网上看,我只能看到如何写入一个子集合而不是两个。

    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
      });
    });
    });

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:

    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 是一个DocumentReference,所以你只需要调用collection 方法来声明这个文档的子集合(即CollectionReferences)。

    【讨论】:

    • 刚刚尝试过,它对您来说绝对是传奇。干杯,我很感激它
    • 很高兴能帮到你!请采纳答案,见stackoverflow.com/help/someone-answers
    • 谢谢,我会的。就一个问题。我想了解我学到的一切,我想知道您是否可以解释 await/async 方法发生了什么以及它是如何工作的?干杯
    • 请查看我在回答的第一句话中添加的async/await 链接。
    • 使用 Future.wait([]) 以获得更好的结果,同时运行期货而不是线性:api.dart.dev/stable/2.1.0/dart-async/Future/wait.html
    猜你喜欢
    • 2020-09-24
    • 1970-01-01
    • 2020-06-15
    • 2020-12-28
    • 2019-09-13
    • 2020-09-20
    • 1970-01-01
    • 2018-10-08
    相关资源
    最近更新 更多