【问题标题】:Multiple "in" filters in Firestore queryFirestore 查询中的多个“in”过滤器
【发布时间】:2021-12-28 21:25:17
【问题描述】:

我有一个方法可以接收用户输入,然后根据所选过滤器查询 Cloud Firestore 数据库。但要获得我需要的结果,我必须使用多个“in”运算符执行查询。有人有解决方法吗? 我的方法:

      getGrouped: async function () {
        let array = [];
        const groupedQuery = query(
          collectionGroup(db, "grouped"),
          where("owner", "==", match.params.uid),
          where("capaign", "in", this.capaign),
          where("region", "in", this.region)
        );
        const groupedSnapshot = await getDocs(groupedQuery);
        groupedSnapshot.forEach((doc: any) => {
          array.push(doc.data());
        });
        return array;
      },    

用户输入如下所示:["CA", "BO", "TX"]

【问题讨论】:

  • 这是一个记录在案的限制:每个查询最多可以使用一个 in、not-in 或 array-contains-any 子句。您不能在同一个查询中组合这些运算符。
  • 还有其他方法可以达到这个效果吗?用户输入是我想用作过滤器的值数组

标签: javascript firebase google-cloud-firestore


【解决方案1】:

Firestore 仅允许每个查询使用一个 in 条件。您需要在 JavaScript 中执行第二个处理结果。

  getGrouped: async function () {
    let array = [];
    const groupedQuery = query(
      collectionGroup(db, "grouped"),
      where("owner", "==", match.params.uid),
      where("capaign", "in", this.capaign)
    );
    const groupedSnapshot = await getDocs(groupedQuery);
    groupedSnapshot.forEach((doc: any) => {
      if (this.region.includes(doc.get('region'))) {
        array.push(doc.data());
      }
    });
    return array;
  },    

【讨论】:

  • 为了快速过滤结果,在比较中使用doc.get("region"),然后在确认文档位于正确区域后使用array.push(doc.data()),您可能会获得边际提升。
  • 就像我说的,我不使用 Firebase。我试图在文档中找到读取字段的语法,但找不到,所以我认为这是正常的属性访问。我已经更新了答案。
猜你喜欢
  • 2020-06-13
  • 1970-01-01
  • 2013-01-01
  • 1970-01-01
  • 2020-11-30
  • 2018-11-27
  • 1970-01-01
  • 1970-01-01
  • 2019-09-03
相关资源
最近更新 更多