javascript - 在单个事务中通过 id 从 firestore 获取多个文档

标签 javascript firebase google-cloud-firestore

我有存储在 players 中的 firestore 文档 ID 列表。现在我想获取所有具有这些 id 的文档。

我可以使用 queryin 运算符,但这仅限于 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/

相关文章:

java - struts 2中将java bean转换为json数据

android - 由于错误,无法在Firestore中更新阵列

firebase - 如果我第二天打开应用程序,Firestore 是否会再次收取文档读取费用?

javascript - 网络上的 Firestore 离线持久化

javascript - 在 Firebase 中写入数据后读取数据

firebase - 如何等待文件上传到 Flutter 中的 Firebase 存储?

javascript - 花式框单击不打开,需要双击

javascript - 如何从 javascript 控制台动态下载和运行 javascript 脚本?

javascript - 滚动到顶部 react react 路由器DOM页面更改

javascript - 使用 Admin SDK 批量写入 Firestore