简体   繁体   中英

Query subcollection in firestore by ID, version 9

The current issue with my current react native/firebase is querying the comments for each post in my forum page in my app. When a user goes to the forum section all the posts in my forums database load correctly but when trying to get the comments for each post by comparing the ID's of the different posts, react native does not allow me to do this and says: Invalid collection reference. Collection references must have an odd number of segments how would i fix this???

  useEffect(() => {
   async function ddd() {
    let todos = []
 // uid is already declared in my app and refers to the id of the post document
      try {
        const url = collection(db, `forums`,"comments");
    const q = query(url,where("uid","==",uid);
        const querySnapshot = await getDocs(q);
        querySnapshot.forEach((doc) => {
          // doc.data() is never undefined for query doc snapshots
          console.log(doc.data());
          todos.push(doc.data())
        });
        
      }
      catch(E){
        alert(E)
      }
      setData1(todos)
   }
   ddd()
  }, [])

firestore structure: 在此处输入图像描述

To load/query the comments for a specific forum, you must specify the forum ID in the path here:

const url = collection(db, "forums", "the forum ID such as R3SXOkxj...", "comments");

If you want to query across all collections named comments , you can use a collection group query , which would look like:

const url = collectionGroup(db, "comments");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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