Kirk Ross
Kirk Ross

Reputation: 7163

Firestore - Web version 9 - get all documents in collection whose id is in array of ids

I'm new to Firestore and trying to form a query to return all documents whose doc.id is in an array of ids.

So something like this:

const getAlbumSongs = async (songUids) => {
    let albumSongs = [];
    const q = query(collection(db, 'songs'), where('id', 'in', songUids));
    const snap = await getDocs(q);
    if (snap) {
      for (const doc of snap) {
        albumSongs.push({
          songId: doc.id,
          albumId: doc.data().album_id,
          authorId: doc.data().author_id,
          songTitle: doc.data().song_title,
          filePath: doc.data().file_path,
        });
      }
    }
    return albumSongs;
  };

I should note I'm calling the getAlbumSongs() function from within a getAlbums() function, like this:

  async function getAlbums() {
    setIsLoadingAlbums(true);
    const snap = await getDocs(collection(db, 'albums'));
    setIsLoadingAlbums(false);
    let albumsData = [];
    if (snap) {
      snap.forEach(async (doc) => {
        albumsData.push({
          ablumId: doc.id,
          albumTitle: doc.data().album_title,
          albumCoverUrl: doc.data().cover_url || 'https://picsum.photos/300',
          albumSongs: await getAlbumSongs(doc.data().song_uids), // this might be problematic?
        });
      });
      console.log('albumsData', albumsData);
      return albumsData;
    }
  }

Upvotes: 1

Views: 993

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599946

Your current code queries on a field called id in each document. If you want the document ID itself, that is part of the metadata of the document and you'll want to query on documentId() for that:

const q = query(collection(db, 'songs'), where(documentId(), 'in', songUids));

Upvotes: 4

Related Questions