繁体   English   中英

如何使用 Reactjs 按参考值过滤 Firestore 特定集合的文档数据

[英]How to filter Firestore specific collection's doc data by its reference value with Reactjs

我有两个 collections section1section2 集合section2有一个字段doc_id ,它是一个reference类型字段,表示section1seciton2之间的关系。

在此处输入图像描述

我想从section2中检索doc_id字段的给定值的数据。 检查示例代码,当我使用任何其他字段(例如district过滤数据时它工作正常。 但它不适用于引用字段类型字段

这给出了预期的结果

const getDocumentData = async () => {
    const q = query(
      collection(db, "section2"),
      where("district", "==", "dhanbad")
    );

    const querySnapshot = await getDocs(q);
    querySnapshot.forEach((doc) => {
      console.log(doc.id, " => ", doc.data());
    });

代码有效,但我没有得到值。 它返回 null。

   const getDocumentData = async () => {
    const q = query(
      collection(db, "section2"),
      where("doc_id", "==", "H0ovBXfrwen32Xb4Ig9A")
    );

    const querySnapshot = await getDocs(q);
    querySnapshot.forEach((doc) => {
      console.log(doc.id, " => ", doc.data());
    });

正如您在屏幕截图中看到的,文档引用字段等同于对该文档的整个引用(从数据库的根目录开始)。 因此,您不能只指定文档 ID,而必须指定实际的文档引用。

const docRef = doc(db, "section1", "H0ovBXfrwen32Xb4Ig9A");
where("doc_id", "==", docRef)

另请参阅 Renaud 的回答: Querying by a field with type 'reference' in Firestore

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM