在单个事务中通过 id 从 firestore 获取多个文档
get multiple docs from firestore by id in single transaction
我有存储在 players
中的 firestore 文档 ID 列表。现在我想获取所有具有这些 ID 的文档。
我可以使用 query
和 in
运算符,但这仅限于 10 个单独的值,我希望情况超过 10 个。Whosebug
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() }))
})
我在他们使用 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 开销。
因此,一种方法是执行多个查询,每个查询将使用 in
运算符以及 Promise.all()
至 运行 并行获取最多 10 个文档。
我有存储在 players
中的 firestore 文档 ID 列表。现在我想获取所有具有这些 ID 的文档。
我可以使用 query
和 in
运算符,但这仅限于 10 个单独的值,我希望情况超过 10 个。Whosebug
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() }))
})
我在他们使用 getAll
的地方偶然发现了这个
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 开销。
因此,一种方法是执行多个查询,每个查询将使用 in
运算符以及 Promise.all()
至 运行 并行获取最多 10 个文档。