繁体   English   中英

使用 Firestore 中的特定字段从集合中获取文档

[英]Get document from collection using specific field in firestore

我希望通过使用带有 Node.js 的formId中的formId字段来获取文档。 formId在地图中,所以我不确定如何使用get()函数。 这是我没有工作的 React 代码。 我相信它不起作用,因为formId字段包含在formMetaData映射中。

    useEffect(() => {
        const firestoreRef = firebase.firestore().collection('Forms');
        // Create a query against the collection where we can match the formId
        const queryRef = firestoreRef.where('formId', '==', ID_HERE);

      }, []);

这里也是数据库的设置: 在此处输入图片说明

谢谢!

使用点表示法访问嵌套字段:

useEffect(() => {
  const firestoreRef = firebase.firestore().collection('Forms');
  // Create a query against the collection where we can match the formId
  const queryRef = firestoreRef.where('formMetaData.FormId', '==', ID_HERE); 
                                                  ^^^
  queryRef.get().then((querySnapshot) => {
    // total matched documents
    const matchedDocs = querySnapshot.size
    if (matchedDocs) {
      querySnapshot.docs.forEach(doc => {
        console.log(doc.id, "=>", doc.data())
      })
    } else {
      console.log("0 documents matched the query")
    }
  })
}, []);

queryRef是一个Query并且具有get()方法,该方法返回一个包含QuerySnapshot的 Promise。

docs上QuerySnapshot属性是数组QueryDocumentSnapshot并且可以使用data()方法在每个DocumentSnapshot访问它的数据。

您可以通过如下更新您的代码,通过formMetaData对象访问formId

useEffect(() => {
    const firestoreRef = firebase.firestore().collection('Forms');
    // Create a query against the collection where we can match the formId
    const queryRef = firestoreRef.where('formMetaData.formId', '==', ID_HERE);

  }, []);

暂无
暂无

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

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