我正在开发一个React项目,在这个项目中,我想要列出已登录用户的文档。结构如下,我想要读取的文档位于集合中。
数据库结构如下:
users(集合) -> user(文档) -> repos(集合) -> repo(文档) -> files(集合) -> files(文档)
我想要读取的是repo(文档)。(它还有一些其他字段)。
这是我尝试的代码:
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());
}
错误信息:
FirebaseError: 期望的类型是 'DocumentReference',但实际上是:一个自定义的CollectionReference对象
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如果您只想查询一个文档,则需要指定您的仓库文档 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())如果您想查询所有仓库,则需要查询集合:
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()) });您可以在此处找到更多相关信息。