我有存储在 players
中的 firestore 文档 ID 列表。现在我想获取所有具有这些 id 的文档。
我可以使用 query
和 in
运算符,但这仅限于 10 个单独的值,我预计情况会超过 10 个。 stackoverflow
const colRef = collection(db, "Products");
const q = query(colRef, where(documentId(), 'in', players));
getDocs(q).then((snap) => {
console.log(snap.docs.map(d => ({ id: d.id, ...d.data() }))
})
我偶然发现了这个question他们使用 getAll
,但此功能在 firestore 9 AFAIK 中不可用。
async getUsers({userIds}) {
const refs = userIds.map(id => this.firestore.doc(`users/${id}`))
const users = await this.firestore.getAll(...refs)
console.log(users.map(doc => doc.data()))
}
我可以创建一个文档引用列表并使用 Promise.all 获取数据,但这将并行运行请求,这会带来额外的成本,因为 firestore 是按请求而不是按每个请求计费的实时数据库中的数据量。
最佳答案
they are using getAll, but this function is not available in firestore 9 AFAIK.
是的,getAll()
是服务器端 NodeJS SDK 的一部分,而不是 Firebase 客户端 SDK 的一部分。
which comes with additional cost as firestore gets billed per request
Firestore 读取按获取的文档数量收费,无论您运行多少个查询,即 5 个查询(每个查询获取 10 个文档)的读取费用与单个查询 50 个文档的读取费用相同。最多您需要支付 SSL 开销,具体取决于连接。
因此,一种方法是执行多个查询,每个查询最多可获取 10 个文档,每个查询都使用 in
运算符以及 Promise.all()
来并行运行它们。
关于javascript - 在单个事务中通过 id 从 firestore 获取多个文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72105332/