簡體   English   中英

Firestore - Web 版本 9 - 獲取集合中其 ID 在 ID 數組中的所有文檔

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

我是 Firestore 的新手,正在嘗試形成一個查詢以返回其 doc.id 在 id 數組中的所有文檔。

所以像這樣:

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;
  };

我應該注意到我是從 getAlbums() function 中調用 getAlbumSongs() function,如下所示:

  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;
    }
  }

您當前的代碼查詢每個文檔中名為id的字段。 如果您想要文檔ID 本身,那是文檔元數據的一部分,您需要在documentId()上查詢:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM