#Help with Firestore + Angular

3 messages · Page 1 of 1 (latest)

jagged canyon
#

Hello guys, i need some help to validate my workflow with firestore 🙂

My feature is about allowing a user to add movies/tvshow to a favorite list.
For that, i designed this structure on firestore (Structure in Copy)

So, each user can create a favorite collection, and each favorite document adds an attribute media which is a DocumentRef inside the medias collection.

I’m using TMDB API to retrieve all media information, and for the favorite feature, i need to store snapshots of each media and each language that my app supports.

The advantage of this structure is that the media data is not duplicated across all users.

On the code side, I am retrieving all this data with the following code (Code in Copy)

I need to understand if i’m on the right way to achieve this (structure + code) for best perfomances 🙂

Thanks

#
medias (collection)
|--- movieId1 (document)
     |--- fr
          |--- { id: XXX, title: XXX, ...}
     |--- en
          |--- { id: XXX, title: XXX, ...}
|--- movieId2 (document)
     |--- fr
          |--- { id: XXX, title: XXX, ...}
     |--- en
          |--- { id: XXX, title: XXX, ...}

users (collection)
|--- userId1 (document)
|    |--- favorites (subcollection)
|         |--- favoriteId1 (document)
|              |--- media: Reference to movieId1
|         |--- favoriteId2 (document)
|              |--- media: Reference to movieId2
|--- userId2 (document)
|    |--- favorites (subcollection)
|         |--- favoriteId1 (document)
|              |--- media: Reference to movieId1
|         |--- favoriteId2 (document)
|              |--- media: Reference to movieId2
#
// userFavoriteCollectionRef is the reference to the user favorite sub-collection
collectionData(this.userFavoriteCollectionRef).subscribe(
    async mediaRefList => {
      // Debug time performances
      console.time();

      // Log all the 264 medias refs from the connected user
      console.log('DATA : ', mediaRefList);

      const mediaPromises = mediaRefList.map(mediaRef =>
        getDoc(mediaRef.media)
      );

      // Get media doc data for each documents (264 here)
      const mediaDocSnaps = await Promise.all(mediaPromises);
      const mediaList = mediaDocSnaps.map(docSnap => docSnap.data());

      // End debug time performances: 634.279052734375 ms for 264 items
      console.timeEnd();
      
      // Debug to see the first element value, and everything is ok
      const firstMedia = mediaList[0] as
        | { [key: string]: TMDBMovie | TMDBTvShow }
        | undefined;

      console.log('FIRST MEDIA FR  : ', firstMedia?.['fr']);
      console.log('SECOND MEDIA EN  : ', firstMedia?.['en']);
    }
  );