在Firestore中存储多层数据

huangapple go评论70阅读模式
英文:

Storing data in firestore for multiple layers

问题

我需要在多个级别上存储数据:
Test 1 > q1, q2, q3... > question: hello, answer: opt 2, opt 1: a, opt 2: b, opt 3: c, opt 4: d

所以实际上,我有多个测试,每个测试中有多个问题,每个问题都有多个选项。

如何将其添加到Firestore,并能够快速加载每个测试,因为目前以下代码的加载速度很慢:

for (var i = 1; i < totalquestions + 1; i++) {
  await FirebaseFirestore.instance
      .collection("users")
      .doc(user!.uid)
      .collection('Test $no')
      .doc(i.toString())
      .set(
        Map<String, dynamic>.from(
          Provider.of<Question>(context, listen: false)
              .question[i]!,
        ),
      );
  await FirebaseFirestore.instance
      .collection("users")
      .doc(user.uid)
      .collection('Test $no')
      .doc(i.toString())
      .update(
    {
      'yourAns':
          Provider.of<Question>(context, listen: false)
              .answers[i]!
              .values
              .first
    },
  );
}
英文:

I need to store data on multiple levels:
Test 1 &gt; q1, q2, q3... &gt; question: hello, answer: opt 2, opt 1: a, opt 2: b, opt 3: c, opt 4: d

So in actual terms I have multiples tests where in each test you have multiple questions and where each question has multiple options.

how can I add it to firestore and be able to load each test fast as at the moment it is delayed for long with the below code:

for (var i = 1; i &lt; totalquestions + 1; i++) {
  await FirebaseFirestore.instance
      .collection(&quot;users&quot;)
      .doc(user!.uid)
      .collection(&#39;Test $no&#39;)
      .doc(i.toString())
      .set(
        Map&lt;String, dynamic&gt;.from(
          Provider.of&lt;Question&gt;(context, listen: false)
              .question[i]!,
        ),
      );
  await FirebaseFirestore.instance
      .collection(&quot;users&quot;)
      .doc(user.uid)
      .collection(&#39;Test $no&#39;)
      .doc(i.toString())
      .update(
    {
      &#39;yourAns&#39;:
          Provider.of&lt;Question&gt;(context, listen: false)
              .answers[i]!
              .values
              .first
    },
  );
}

答案1

得分: 1

将此发布为社区wiki,以便所有人都能看到。

正如Frank所提到的,Firestore中的嵌套字段在Flutter中会被翻译成嵌套的Map对象。需要考虑的一件事是嵌套字段是否应该是子集合中的documents。这将使您能够单独查询它们并加载数据子集,但会导致您读取更多文档。在这里有一个关于Flutter中嵌套地图的综合答案。

答案链接

英文:

Posting this as a community wiki for everyone's visibility.

As mentioned by Frank, nested fields in Firestore translate to nested Map objects in Flutter. A thing to consider is whether the nested field should be documents in a subcollection. It will enable you to query them separately and load subsets of data, but you'll end up reading more documents. Here's a comprehensive answer on nested Maps in flutter.

huangapple
  • 本文由 发表于 2023年6月6日 04:06:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76409672.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定