javascript - 如何使用 `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"
自动生成的列的名称是否正确?
解决方案
要通过 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”。
推荐阅读
- pandas - 以正确的格式读取日期
- javascript - 加载没有“新图像()”的图像
- gradle - 从 gradle 中的几个冲突的传递依赖项中强制执行最高版本
- css - Is there a way to keep the content inside a mat-card responsive?
- python - Filtering languages queryset looping on tuple (code, name_translated)
- r - 如何验证开源 R 包;即消除恶意包
- php - 如何使用 PHP 和 MYSQL 在表中插入多行?
- sql - Dtd 或 Xsd Sql 定义
- batch-file - 使用包含 10,000 个项目的列表时批处理文件崩溃
- node.js - How to read an image and text at the same time in Loopback/NodeJs