Here's the setup I have on my Cloud Firestore:
Collection question:
- userID
- text
and Collection user:
- name
- key
I am able to easily retrieve the question data from the database and display it, but currently without the user data. Then, I need to perform another search in the database for each comment that was previously retrieved. However, I am encountering numerous difficulties trying to accomplish this.
First:
I start by searching for the questions:
Component:
export class ListQuestionsComponent implements OnInit {
tableData: Question[] = [];
userData: User[] = [];
constructor(
private questionService: QuestionService,
private userService: UserService,
) { }
ngOnInit() {
this.loadItems();
this.getUsers();
}
loadItems() {
this.questionService.loadItems().subscribe(response => {
this.tableData = [];
for (const item of response) {
this.tableData.push(item.payload.doc.data() as Question);
}
}
Question Service:
loadItems() {
const query = ref => ref
.limit(10);
return this.firestore.collection('perguntas', query).snapshotChanges();
}
This successfully fetches the questions and populates the tableData array. Now, I need to find the respective user for each of these questions.
I attempted to do this within the same Component:
getUsers() {
for(const item of this.tableData) {
this.userService.getUserByKey(item.userID).subscribe(response => {
this.userData = [];
for (const user of response) {
this.userData.push(user.payload.doc.data() as User);
}
});
}
}
User Service
getUserByKey(key: string) {
return this.firestore.collection('users', ref => ref
.where('key', '==', key))
.snapshotChanges();
}
After all this, I have a tableData with 10 questions, but userData remains empty. I am unsure of what to do next. My goal is to retrieve only the users who are associated with the questions I've fetched.