[英]How to list all documents in a sub-collection and then fetch their documents by their ID?
我正在尝试在“学生”和他们的“课程”之间的集合中显示文档中的数据
我正在使用 html、javascript 和此结构,但到目前为止我只能检索文档的 ID,但我还想访问此文档中的数据
async function fetchCourses() {
const studentId = firebase.auth().currentUser.uid
const courseIds = await db.collection(`students/${studentId}/attending`).get();
const courseDocs = await Promise.all(
courseIds.docs.map(doc => db.doc(`courses/${doc.id},${studentId}`).get())
);
return courseDocs.filter(doc => doc.exists).map(doc => ({ id: doc.id, ...doc.data() }),
console.log(courseDocs));
}
我的 console.log 显示所有这些:
任何帮助都将不胜感激
编辑
这是我的 Firebase 内部的数据结构:
学生存储在一个由他们的 uid 索引的集合中,每个学生文档都包含他们的姓名和更多数据,但最重要的是一个名为参加的子集合,其中包含由 courseId 索引的空文档,引用课程集合中的文档
课程存储在另一个由 courseId 索引的集合中,就像学生一样,每个课程文档都包含一个标题和更多数据,以及一个名为参加者的子集合,其中包含由 uid 索引的空文档,指的是学生。
import { doc, getDoc } from "firebase/firestore";
const docRef = doc(db, "cities", "SF");
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("Document data:", docSnap.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
以上是来自 firestore 文档的示例。 firestore具有非常特定的语法。 您只能使用 doc.data() 语法访问请求数据。 所有其他尝试都不会给你带来任何东西或一些不相关的东西(至少在我的经验中)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.