【问题标题】:How to check documentid contains a substring from firestore?如何检查 documentid 是否包含来自 Firestore 的子字符串?
【发布时间】:2021-09-10 15:01:34
【问题描述】:
import firebase from "../firebase";
import React, { useState, useEffect } from "react";
import { useLocation } from "react-router-dom";

const Result = (props) => {
  const { state } = useLocation();
  const { exam, category, councelling, branch, gender, rank } = state.state;
  const [result, setResult] = useState([]);

  const db = firebase.firestore();
  const que = category + "_" + gender + "_CR";
  const docref = db
    .collection(exam)
    .doc("2019-2020")
    .collection("RankAnalysis")
    .where(
      (firebase.firestore.FieldPath.documentId()
        .toString()
        .substring(
          firebase.firestore.FieldPath.documentId().toString().length -
            branch.length
        ),
      "==",
      branch)
    )
    .where(rank, "<", que);

  useEffect(() => {
    const fetchData = async () => {
      docref
        .get()
        .then((querySelector) => {
          querySelector.forEach((doc) => {
            console.log(doc.data());
          });
        })
        .catch((error) => {
          console.log("Error getting documents: ", error);
        });
    };

    fetchData();
  }, [docref]);

  return (
    <div>
      <h1>{exam}</h1>
      <h1>{branch}</h1>
      <h1>{category}</h1>
      <h1>{gender}</h1>
      <h1>{councelling}</h1>
      <h1>{rank}</h1>
    </div>
  );
};

export default Result;

关键是我想从firestore中获取文档,该文档最后特别包含一个子字符串(即分支),所以我使用了 fieldpath.documentId() 它返回一个字段路径(我将其转换为字符串),但似乎什么都没有解决。 数据库的结构如下:-

文档名称类似于 AAAACSE 我想获取包含子字符串“CSE”(动态)的文档。

【问题讨论】:

    标签: javascript reactjs google-cloud-firestore react-router


    【解决方案1】:

    Firestore 无法过滤以特定子字符串结尾的 ID/值。它可以处理的唯一字符串条件是“相等”(通过==)和“开始于”(通过&gt;=&lt;=)。

    因此,在 Firestore 中实现您的用例的唯一方法是尊重 ID 并对其进行过滤。

    如果您需要更强大的文本过滤功能,请考虑为此使用另一种/额外的解决方案 - 例如 adding full-text search to Firestore 上的 Firebase 文档中所示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-09
      • 2013-05-18
      • 1970-01-01
      • 2011-03-29
      • 2021-12-20
      • 2010-12-19
      • 2012-01-05
      相关资源
      最近更新 更多