如何在 Firebase 实时数据库中获取多个文档 ID?

问题描述 投票:0回答:1

我的目标是一次获取多个文档。

问题是,除了一一获取,我不知道该怎么做。

我尝试过的:

  1. 循环调用
    fetchByDocumentIdHelper
    ,每个请求花费600ms。这是不可扩展的。
  2. 尝试使用
    onValue
    。但是,我不知道如何获取特定的 documentId。

此函数用于获取 1 个文档。

async function fetchByDocumentIdHelper(
  database: Database,
  documentId: string
): Promise<AgencyRealtimeModel> {
  const dbRef = ref(database);
  const query = child(dbRef, `agencies/${documentId}`);
  const dataSnapshot = await get(query);

  if (!dataSnapshot.exists()) {
    return {};
  }

  const id = documentId;
  const data = dataSnapshot.val();

  const model: AgencyRealtimeModel = {
    id: id,
    data: data,
  };

  return model;
}

此功能是获取多个文档

async function fetchByDocumentIdsHelper(
  database: Database,
  documentIds: string[]
): Promise<AgencyRealtimeModel[]> {
  const models: AgencyRealtimeModel[] = [];

  for (let i = 0; i < documentIds.length; i++) {
    const documentId = documentIds[i];
    const model = await fetchByDocumentIdHelper(database, documentId);
    models.push(model);
  }

  return models;
}
firebase firebase-realtime-database
1个回答
0
投票

目前,我将使用 Promise.all

async function fetchByDocumentIdsHelper(
  database: Database,
  documentIds: string[]
): Promise<AgencyRealtimeModel[]> {
  const models: AgencyRealtimeModel[] = await Promise.all(
    documentIds.map(async (documentId) => {
      const dbRef = ref(database);
      const query = child(dbRef, `agencies/${documentId}`);
      const dataSnapshot = await get(query);

      const id = documentId;
      const data = dataSnapshot.val();

      const model: AgencyRealtimeModel = {
        id: id,
        data: data,
      };

      return model;
    })
  );

  return models;
}
© www.soinside.com 2019 - 2024. All rights reserved.