Problems trying to fetch Cloud Firestore data

Okay, i have this structure on my Cloud Firestore:

Collection question:
- userID
- text

and Collection user:
- name 
- key

I can easily retrieve the question data from the database and return it, but without the user data for now. Them i need do another search in database foreach comment returned previously. However I am having a lot of problems trying to do this.


I do this for search the questions:


export class ListQuestionsComponent implements OnInit {
  tableData: Question[] = [];
  userData: User[] = [];

      private questionService: QuestionService,
      private userService: UserService,
  ) { }

 ngOnInit() {

loadItens() {
    this.questionService.loadItems().subscribe(response => {
      this.tableData = [];
      for (const item of response) {
        this.tableData.push( as Question);

Question Service:

loadItems() {
    const query = ref => ref

    return this.firestore.collection('perguntas', query).snapshotChanges();

This works and now I have the questions in my tableData. Now I need search the user for each of this questions.

I try do this in 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( as User);

User Service

getUserByKey(key: string) {
    return this.firestore.collection('users', ref => ref
      .where('key', '==', key))

At end of all I have a tableData with 10 questions, and userData without nothing. I don't know what to do now. I only need the users who are referenced in the questions I sought.

2 answers

  • answered 2019-09-16 02:10 Dan Fein

    There are a lot of approaches, the methodology that I've adopted with Firestore is to store the data that I think I will need with the data I'm pulling.

    So if I were to pull questions and I know I will need a user, their username, and their profile picture, then I will store a user field in each question document that has the user's ID, username, and profile picture.

    Something like:

    ---> Question
    ---> Date
    ---> User:
    -------> ID
    -------> Profile Picture
    -------> Username

  • answered 2019-09-16 16:26 Misael Brunoro Liberato

    Well, researching a little about asynchronous function has achieved some result. I changed some things in the code.

    Variable user data become

    userData: any;

    Inside of the subscribe of my loadItems() i call getUsers()

    and my getUsers()

    getUsers() {    
      for (const item of this.tableData) {
        this.usuarioService.getUserByKey(item.userId).subscribe(response => {
          this.userData[item.userId] = response[0];