首页 > 解决方案 > 如何使用 `in` 子句从 firestore 集合中获取具有特定 ID(复数)的文档?

问题描述

我已经阅读了一些关于该主题的帖子,但由于某种原因,我无法获取我需要的文档。我有一个users带有自动生成 ID 的集合,每个文档都包含名称和电子邮件。这是我的收藏: 在此处输入图像描述

请注意,ID 是自动生成的。

然后,我尝试在代码中执行以下操作:

firebase.firestore()
        .collection("users")
        .where(
          "id",
          "in",
          ids
        )
        .get()
        .then((querySnapshot) => {
            const people = [];
            querySnapshot.forEach(documentSnapshot => {
              people.push({
                  ...documentSnapshot.data(),
                  key: documentSnapshot.id
                  });
                });
              console.log("people: ", people);
          });

我的people数组是空的。我很确定我的ids数组具有正确的 ID。我不确定这部分是否正确:

firebase.firestore()
        .collection("users")
        .where(
          "id",
          "in",
          ids
        )
        .get()

"id"自动生成的列的名称是否正确?

标签: javascriptfirebasereact-nativegoogle-cloud-firestore

解决方案


要通过 ID 查询文档,您应该使用firebase.firestore.FieldPath.documentId()which 返回一个特殊值,该值可与where()过滤器一起使用以通过文档 ID 进行搜索。


以下代码已根据此记录的要点(Typescript/JavaScript)进行了调整:

function chunkArr(arr, n) {
  if (n <= 0) throw new Error("n must be greater than 0");
  return Array
    .from({length: Math.ceil(arr.length/n)})
    .map((_, i) => arr.slice(n*i, n*(i+1)))
}

async function fetchDocumentsWithId(collectionQueryRef, arrayOfIds) {
  // in batches of 10, fetch the documents with the given ID from the collection
  const fetchDocsPromises = chunkArr(arrayOfIds, 10)
    .map((idsInChunk) => (
      collectionQueryRef
        .where(firebase.firestore.FieldPath.documentId(), "in", idsInChunk)
        .get()
    ))

  return Promise.all(fetchDocsPromises)
    .then((querySnapshotArray) => {
      const allDocumentsArray = [];
      for (let querySnapshot of querySnapshotArray) {
        querySnapshot.forEach(doc => allDocumentSnapshotsArray.push({...doc.data(), key: doc.id}))
      }
      return allDocumentsArray;
    });
}

const usersColRef = firebase.firestore()
        .collection("users");
const ids = [ /* ... */ ];

const docDataArray = fetchDocumentsWithId(usersColRef, ids);

如果您要使用未经编辑的 gist版本,您将改为使用:


const usersColRef = firebase.firestore()
        .collection("users");
const ids = [ /* ... */ ];
const docDataArray = [];

await fetchDocumentsWithId(usersColRef, ids, (doc) => docDataArray.push({ ...doc.data(), key: doc.id }))

console.log(docDataArray)

注意:我会避免对 Firestore 使用术语“key”,而是使用“id”。如果您在文档中使用“id”,则始终可以使用“_id”。


推荐阅读