【问题标题】:Check if specific element exists in firestore document array检查firestore文档数组中是否存在特定元素
【发布时间】:2022-01-05 05:49:16
【问题描述】:

我有一个名为'products' 的集合,在'products' 内部,我有一个名为'W2TO2uQlQ3T2iEvxxom3'document 在此文档中,我有一个名为 Productsarray。 在这个数组里面,我有很多mappings。在each map里面,有several elements

查询:如何确定某个特定元素是否存在于 Products 的映射中。 之后,我想打印每个包含特定元素的映射,例如“id : v3IzhvjVHKhmFK16OvWnHs8wOjm2”

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    您可以尝试从 Firestore 获取包含 products 数组的文档。从文档的data(这是一个Map<String, dynamic>类型),可以遍历到products数组。使用 where() method,您可以根据谓词(例如具有特定 ID)过滤数组。您可以将其与 toList() method 结合使用,以便将所有匹配的映射分组到一个列表中。

      FirebaseFirestore firebase = FirebaseFirestore.instance;
      firebase
      .collection("products")
      .doc("prodArrayDoc") // Document which contains the products array
      .get()
      .then((doc) {
        var prodList = doc.data()?["products"].where((x) => // Traversing the data of the document to the products array
          x?["category"] == "Electronics" // Predicate to filter the array by
        ).toList();
    
        print(prodList);
      });
    

    我为这个 sn-p 重新创建了你的结构,我的数组有几个与“电子”类别的映射,所有匹配的都返回:

      [{id: testProduct2, name: phone, category: Electronics}, {category: Electronics, name : speakers, id: testProduct3}]
    

    如果您的用例可能,将每个产品作为文档直接存储在 products 集合中,您可以根据 FlutterFire docs 以更直接的方式进行查询。

    【讨论】:

    • 如果此答案对您有所帮助,您可以单击复选标记图标将其标记为已接受。这可以帮助遇到同样问题的未来用户。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2020-06-08
    • 1970-01-01
    • 2018-08-05
    • 2021-11-09
    • 2019-04-19
    相关资源
    最近更新 更多