Firestore通过ID数组获取指定文档失败,求解决办法
解决Firestore按文档ID数组获取文档的报错问题
错误原因分析
db.getAll is not a function:getAll是Firestore Admin SDK专属API,你使用的客户端Web SDK(@firebase/firestore)不包含该方法,客户端需通过getDoc配合Promise.all实现批量获取。FieldPath.documentId is not a function:客户端SDK中,documentId是独立导出的函数,并非FieldPath的属性方法,需单独导入使用。
正确实现方法
方法一:批量获取单个文档(替代getAll)
通过Promise.all并行请求所有目标文档:
import { getApp } from "@firebase/app"; import { getFirestore, doc, getDoc } from "@firebase/firestore"; const db = getFirestore(getApp()); // 生成所有目标文档的引用 const docRefs = array.map(itemId => doc(db, `collection/document/collection`, itemId)); // 并行获取所有文档数据 const docs = await Promise.all(docRefs.map(ref => getDoc(ref))); // 过滤有效文档并提取数据 const result = docs.filter(doc => doc.exists()).map(doc => doc.data());
方法二:使用documentId的in查询
修正导入和语法后,通过in查询匹配文档ID数组:
import { getApp } from "@firebase/app"; import { getFirestore, collection, query, where, documentId, getDocs } from "@firebase/firestore"; const db = getFirestore(getApp()); const colRef = collection(db, `collection/document/collection`); // 使用单独导入的documentId函数 const q = query(colRef, where(documentId(), 'in', array)); const querySnapshot = await getDocs(q); // 提取所有查询到的文档数据 const result = querySnapshot.docs.map(doc => doc.data());
注意:Firestore的
in查询单次最多支持传入50个文档ID,若你的array长度超过50,需拆分数组分批查询后合并结果。
内容的提问来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

