简体   繁体   English

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

[英]How do I fetch documents with specific ids (plural) from a firestore collection using the `in` clause?

I already read few post on the topic, but for some reason I can not fetch the docs which I need.我已经阅读了一些关于该主题的帖子,但由于某种原因,我无法获取我需要的文档。 I have a collection users with auto generated id and each doc contains name and email.我有一个具有自动生成 ID 的users集合,每个文档都包含名称和 email。 Here is my collection:这是我的收藏: 在此处输入图像描述

Please note, the ids are auto generated.请注意,ID 是自动生成的。

Then, what I try to do in the code is the following:然后,我尝试在代码中执行以下操作:

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

My people arrays is empty.我的people arrays 是空的。 I am pretty sure that my ids array has the correct ids.我很确定我的ids数组具有正确的 id。 I am not sure if this part is correct:我不确定这部分是否正确:

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

Is "id" the correct name of the auto generated column? "id"是自动生成列的正确名称吗?

To query a document by it's ID, you should make use of firebase.firestore.FieldPath.documentId() which returns a special value that can be used with the where() filter to search by a document's ID.要通过 ID 查询文档,您应该使用firebase.firestore.FieldPath.documentId()来返回一个特殊值,该值可以与where()过滤器一起使用,以通过文档 ID 进行搜索。


The following code has been tweaked from this documented gist (Typescript/JavaScript):以下代码已根据此记录的要点(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);

If you were to use the unedited version of the gist , you would instead use:如果您要使用未经编辑的 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)

Note: I'd avoid using the term "key" for Firestore and instead use "id".注意:我会避免对 Firestore 使用术语“key”,而是使用“id”。 If you are using "id" in your documents, you could always use "_id" instead.如果您在文档中使用“id”,则始终可以使用“_id”。

In this situation I am assuming that ids is an array that you have in your client side code and are looking to query only for those ids in firestore?在这种情况下,我假设ids是您在客户端代码中拥有的一个数组,并且只想查询 firestore 中的那些 id?

Unfortunately, when using the .where() functionality in firestore, it does not query against the document ID's but rather the content of the document.不幸的是,在 firestore 中使用.where()功能时,它不会查询文档 ID,而是查询文档的内容。

If you wanted to use the .where() indexing capability of firestore, you would need to add a uid field to the actual document data.如果您想使用 firestore 的.where()索引功能,则需要在实际文档数据中添加一个uid字段。 Once you do that, you should be able to query for only the ID's you would like.一旦你这样做了,你应该能够只查询你想要的 ID。

From the firestore docs 来自 Firestore 文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从firestore中的文档ID数组中获取所有子集合文档 - How to fetch all subcollections documents from array of document-ids in firestore 如何在 Web v9 中使用“where”子句从 Firestore 集合中删除文档 - How delete documents from a Firestore collection with a 'where' clause in Web v9 如何获取 Firestore 集合中所有文档的子集合的特定文档? - How to get specific Documents of a Subcollection of all Documents in a Collection in Firestore? 获取具有多个 ID 的 Firebase Firestore 文档 - Fetch firebase firestore documents with multiple IDs 如何将我的集合中的文档放入一个对象数组中,这些对象的字段来自 Google Firestore? - How do I put my Documents from my Collection into an array of objects with their own fields getting from Google Firestore? 如何从 Firestore 获取 ID 到 object arrays? - How do I get the IDs from firestore into the object arrays? Firestore - 如何确定地从集合中获取多个随机(非重复的、特定数量的)文档? - Firestore - How to get multiple random (non duplicated, specific number of) documents from a collection with certainty? 如何从 Cloud Firestore 检索多个文档,但没有重复? - How do i retrieve multiple documents from cloud firestore, but no duplicates? 如何使用云功能返回 firestore 中的每个集合及其文档? - How do I return each collection and its documents in firestore with cloud functions? Firestore 规则:如何检查集合中所有文档的 map 的内容? - Firestore rules: How do I check the contents of a map on all documents in a collection?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM