I’m building a school managment system using HTML and Javascript in which, students must attend courses and I’m using this article as a guide: https://medium.com/firebase-tips-tricks/how-to-secure-many-to-many-relationships-in-firestore-d19f972fd4d3
I already have the Write part so I can associate courses with students, in the article this is
the code:
const attendingRef = db.doc(`students/${studentId}/attending/${courseId}`);
const attendeeRef = db.doc(`courses/${courseId}/attendees/${studentId}`);
const batch = db.batch();
batch.set(attendingRef, {});
batch.set(attendeeRef, {});
await batch.commit();
}
But I had to make some changes to make it work in my project:
async function attendCourse() {
const studentId = firebase.auth().currentUser.uid
const courseId = "0O1OZOrtipgw8xlqNINc"
const attendingRef = db.doc(`students/${studentId}/attending/${courseId}`);
const attendeeRef = db.doc(`courses/${courseId}/attendees/${studentId}`);
const batch = db.batch();
batch.set(attendingRef, {});
batch.set(attendeeRef, {});
await batch.commit();
}
Now I want to fetch all the courses that a logged-in student attends and show them in a table, in the article it says that by using this I should be able to fetch the data:
async function fetchCourses(studentId) {
const courseIds = await db.collection(`students/${studentId}/attending`).get();
const courseDocs = await Promise.all(
courseIds.docs.map(doc => db.doc(`courses/${doc.id}`).get())
);
return courseDocs.filter(doc => doc.exists).map(doc => ({ id: doc.id, ...doc.data() }));
}
So I modified the code to make it work with my project aswell like this:
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}`).get())
);
console.log(courseDocs);
return courseDocs.filter(doc => doc.exists).map(doc => ({ id: doc.id, ...doc.data() }));
}
Now, my console.log(courseDocs) shows a lot of things and amongst them is the id of the course that the student is attending but I want to show the title and content of that course in a table, any help is gladly appreciate.