Retrieve documents in a nested collection
P粉682987577
P粉682987577 2024-03-22 13:50:45
0
1
1092

I'm working on a React project in which I want to list documents for logged in users. The structure is as follows, the document I want to read is in the collection.

The database structure is as follows:

users (collection) -> user (document) -> repos (collection) -> repo (document) -> files (collection) -> files (document)

What I want to read is the repo (document). (It also has some other fields).

This is the code I tried:

const userRef = doc(db, "users", userId)
const repoRef = collection(userRef, "repos")

const querySnapshot = await getDocs(repoRef);

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

error message:

FirebaseError: Expected type is 'DocumentReference', but actually: a custom CollectionReference object

P粉682987577
P粉682987577

reply all(1)
P粉418351692

If you only want to query one document, you need to specify your warehouse document ID:

import { doc, getDoc } from "firebase/firestore"

const docRef = doc(db, `users/${userId}/repos/${repoDocId}`);
const docSnapshot = await getDoc(docRef);

console.log("repo doc data:", docSnapshot.data())

If you want to query all warehouses, you need to query the collection:

import { collection, query, where, getDocs } from "firebase/firestore";

const querySnapshot = await getDocs(
  query(collection(db, `users/${userId}/repos`))
)

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

You can find more information here.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template