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粉4183516922024-03-23 09:41:25
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.