0

I'm trying to reach the data when theres a collection, and inside that collection a doc and inside that doc a collection again.

But im not able to do it.

getTeams() {
  this.db
    .doc('epicseven')
    .collection('teams')
    .snapshotChanges()
    .subscribe(data => {
      console.log(data);
    });
}

this is the database.

image 1 image 2

I want to access the JSON with the last array, so i can iterate in the html.

Thanks for your help.

Mystearica
  • 167
  • 1
  • 3
  • 12

2 Answers2

1

I think you mistaken collection for doc in the beginning. 'epicseven' is a collection. After a collection is always a doc and inside a doc there's either a reference to a collection or values itself. Beside you didn't go down deep enough to get the desired data, my guess is you query would only get the name of the team collection since Firestore query is shallow by default. I would suggest the following query:

getTeams() {
  this.db
    .collection('epicseven')
    .doc('teams')
    .collection([TEAM_NAME])
    .doc([ID])
    .valueChanges()
    .subscribe(data => {
      console.log(data);
    });
}
Linh
  • 418
  • 4
  • 9
  • Hi, thanks for your reply. You are right, i was changing the code so at that point was a doc. But I usually was using the collection method. The problem is that I will have different Teams, and i want to iterate them. – Mystearica Feb 05 '19 at 00:08
  • I would work with arguments along the line of `getTeams(teamName, teamId) {...}` and handle picking the right team name/id somewhere else. Or if you need to fetch multiple docs, use the query function instead – Linh Feb 05 '19 at 00:18
  • But if i dont know the ID inside the database, how could i access then? I mean, with your example, i could access, that wasnt a problem, but if i use random ids, will be imposible to access deeper. – Mystearica Feb 05 '19 at 00:20
  • It sounds like you need to query teams, which is a subcollection, this is indeed still [not possible](https://stackoverflow.com/questions/46573014/firestore-query-subcollections). I would suggest you to make a root collection out of 'teams', this way you can query it after properties like teamsize, 'epicseven' can be a property too e.g `league: 'epicseven'` this way u can query the league. – Linh Feb 05 '19 at 00:30
  • In general it is encouraged to keep your database as shallow as possible, meaning not to go deep but go wide with many root collection to enhance queriability. [More on query](https://firebase.google.com/docs/firestore/query-data/queries) – Linh Feb 05 '19 at 00:30
0

use this.

getTeams() {
  this.db
  .collection('epicseven')
  .doc('teams')
  .collection([TEAM_NAME])
  .doc([ID])
  .snapshotChanges()
  .pipe(map(list => list.map(item => {
     let data = item.payload.doc.data();
     let id = item.payload.doc.id;
     return { id, ...data }
   }))).subscribe(res => {
    console.log(res);
  });
}
Balaj Khan
  • 2,490
  • 2
  • 17
  • 30