How Do I Query current ID against ID's in a collection to show only documents with similar fields and value using react Js and Firestore

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

How Do I Query current ID against ID's in a collection to show only documents with similar fields and value using react Js and Firestore

问题

我有两个文档,目前我可以独立查看这些文档,而且相应的ID也可以在我的网址中看到。所以我正在尝试实现的目标是从我的Firebase集合中显示具有相似字段和相似值的文档;例如,如果一个ID(f3aNQYFyv9hpg0ZLikWt)具有一个字段(regNo),另一个ID(Ta0yfjgbq9B30OLTnPzx)也具有一个字段(regNo),并且它们都具有相同的值(regNo: "AFY/2013/6440")。由于我可以使用 useParams 从网址中获取当前ID,我想将其与集合中的文档进行比较,以检查是否有另一个ID具有相似字段的相似值...

所以目前我已经从集合中提取了所有文档:

const [data, setData] = useState([]);

useEffect(() => {
    // 实时监听
    const collectionRef = collection(db, "dentist");
    const q = query(collectionRef, orderBy("timeStamp", "asc"))
    const unsub = onSnapshot(
        q,
        (snapShot) => {
            let list = [];
            snapShot.docs.forEach((doc) => {
                list = [{ id: doc.id, ...doc.data() }, ...list]
            });
            setData(list);
        },
        (error) => {
            console.log(error);
        }
    );
    
    return () => {
        unsub();
    };
}, []);

我尝试做的是将当前ID与集合中的所有ID进行比较,以检查哪些文档具有字段(regNo)的相同值。首先,我要检查是否获取包含具有相似字段和值的数据,这部分代码有效:

const [data, setData] = useState([]);

useEffect(() => {
    const getList = async () => {
        const collectionRef = collection(db, "dentist")
        const q = query(collectionRef, where("regNo", "==", "AFY/2013/6440"))
        await getDocs(q).then((task) => {
            let medData = task.docs.map((doc) => ({...doc.data(), id: doc.id}))
            setData(medData)
            console.log("medData", medData)
        }).catch((err) => {
            console.log(err)
        })
    }
    getList()
}, [])

这实际上返回了具有特定 regNo 的所有文档,但是我想要将当前ID与集合中的所有ID进行比较,这部分代码不起作用,另外我不想硬编码 regNo 的值,因为如果我要比较网址中的当前ID 与集合中的其他ID,它应该循环查看哪些文档共享字段(regNo)的相同值。以下是最后我添加的部分,但返回了错误:

const [data, setData] = useState([]);

const {userId}  = useParams();
let id = userId

useEffect(() => {
    const getList = async (id) => {
        const collectionRef = collection(db,`dentist/${id}`)
        const q = query(collectionRef, where("regNo", "==", "检查相同regNo值(这是我想要它执行的)"))
        await getDocs(q).then((task) => {
            let medData = task.docs.map((doc) => ({...doc.data(), id: doc.id}))
            setData(medData)
            console.log("medData", medData)
        }).catch((err) => {
            console.log(err)
        })
    }
    getList()
}, [id])
英文:

I have two documents, currently I can view the documents independently and the respective ID's can also be seen in my web address. So what I'm trying to achieve is to show document from my firebase collection that has a similar field with similar value; for instance if one of the Id(f3aNQYFyv9hpg0ZLikWt) has a field(regNo) and another Id(Ta0yfjgbq9B30OLTnPzx) with a field(regNo) both having the same value(regNo: "AFY/2013/6440"). Since I can pull the current Id with useParams from the web address, I want to compare it with the documents in the collection to check if there's another Id having similar value from a field...
So currently I've pulled all document from the collection:-

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    const [data, setData] = useState([]);

 useEffect(() =&gt;{
    // LISTEN (REALTIME)
    const collectionRef = collection(db, &quot;dentist&quot;);
    const q = query(collectionRef, orderBy(&quot;timeStamp&quot;, &quot;asc&quot;))
    const unsub = onSnapshot(
      q,
      (snapShot) =&gt; {
        let list = [];
        snapShot.docs.forEach((doc) =&gt; {
          list = [{ id: doc.id, ...doc.data() }, ...list]
         
        });
        setData(list);
      },
      (error) =&gt; {
        console.log(error);
      }
    );
    
    return () =&gt; {
      unsub();
    };
    }, []); 

<!-- end snippet -->

What I tried to do was compare the current Id against all Id's in the collection to check which of the documents has the same value for the field(regNo). I had to first check if I'm getting data containing those similar fields with value, which worked, here's the code:-

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

   const [data, setData] = useState([]);

    useEffect(()=&gt;{
        const getList = async () =&gt; {
            const collectionRef = collection(db, &quot;dentist&quot;)
          const q = query(collectionRef, where(&quot;regNo&quot;, &quot;==&quot;, &quot;AFY/2013/6440&quot;))
          await getDocs(q).then((task)=&gt;{
           let medData = task.docs.map((doc) =&gt; ({...doc.data(),
          id: doc.id}))
          setData(medData)
          console.log(&quot;medData&quot;, medData)
          }).catch((err) =&gt;{
            console.log(err)
          })
        }
        getList()
      }, [])

<!-- end snippet -->

This actually returned every document with that particular regNo but I wanted it to compare the current ID against all the Id's in the collection, which didn't work plus I don't want to hardcode the regNo value, because If I'm to compare the current Id in my web address with the others in my collection, it should loop through to see which documents share the same value for the field(regNo)..
This was what I eventually added that returned an error

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

   const [data, setData] = useState([]);

    const {userId}  = useParams();
    let id = userId

    
    useEffect(()=&gt;{
        const getList = async (id) =&gt; {
            const collectionRef = collection(db,`dentist/${id}`)
          const q = query(collectionRef, where(&quot;regNo&quot;, &quot;==&quot;, &quot;check for the same value of regNo(This is a what I want it to do)&quot;))
          await getDocs(q).then((task)=&gt;{
           let medData = task.docs.map((doc) =&gt; ({...doc.data(),
          id: doc.id}))
          setData(medData)
          console.log(&quot;medData&quot;, medData)
          }).catch((err) =&gt;{
            console.log(err)
          })
        }
        getList()
      }, [id])

<!-- end snippet -->

答案1

得分: 1

使用const collectionRef = collection(db,`dentist/${id}`)定义一个CollectionReference是行不通的,因为路径段数是偶数。您必须有奇数个路径段,例如collIdcollId/docId/suCollIdcollId/docId/suCollId/subDocId/subSubCollId等等...

因此,如果在一个集合中,您知道具有特定regNo值的文档的ID,并且想要获取该集合中所有与其同级的文档,您需要在regNo上使用where子句查询整个集合。

换句话说,您需要:

  1. 获取第一个文档,根据其ID,以获取其regNo
  2. 使用此值查询整个集合
  3. 确定查询结果中不是第一个文档的所有文档(在前端使用循环,根据初始文档ID完成)
英文:

Defining a CollectionReference with const collectionRef = collection(db,`dentist/${id}`) cannot work because there is an even number of path segments. You must have an odd number of path segments, e.g. collId or collId/docId/suCollId or or collId/docId/suCollId/subDocId/subSubCollId, etc...

So, if in a collection you know the ID of a document with a given value for regNo and want to get all its siblings documents in the collection you need to query the entire collection with a where clause on regNo.

In other words you need to:

  1. Fetch the first document, based on its ID, in order to get its regNo Value
  2. Use this value to query the entire collection
  3. Identify all the docs in the query results that are not the first document (to be done with a loop in the front end, based on the initial document ID)

huangapple
  • 本文由 发表于 2023年6月15日 09:54:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76478584.html
匿名

发表评论

匿名网友

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

确定