如何用Node.js获取Firestore文档中的子集合列表?
问题:获取Firestore文档的子集合名称
我是Firebase技术新手,需要获取Firestore中“Class 1”集合下各文档的子集合名称。当前代码仅能获取文档ID及数据,部分文档存在一个或多个子集合,希望得到包含子集合名称(无则为null)的结构化结果。
期望输出示例
const tempDoc = [ //The Result Which I want { id: "One", data : "something-1", sub_collection : null, }, { id: "Two", data : "something-2", sub_collection : ["sub collection - 1", "sub collection - 2"], }, { id: "Three", data : "something-3", sub_collection : ["sub collection"], }, ]
当前实现代码
db.collection("Class 1").get().then((querySnapshot) => { const tempDoc = [] querySnapshot.forEach((doc) => { tempDoc.push({ id: doc.id, ...doc.data() }) // some of doc have one or more sub-collections }) console.log(tempDoc) })
解决方案
要获取文档的子集合,需要调用Firestore提供的doc.listCollections()方法,该方法返回一个Promise,因此需要处理异步逻辑。可以通过Promise.all并行处理所有文档的子集合查询,提升效率。
修改后的代码如下:
db.collection("Class 1").get().then(async (querySnapshot) => { // 为每个文档生成获取子集合的异步任务 const docTasks = querySnapshot.docs.map(async (doc) => { // 获取当前文档的所有子集合 const subCollections = await doc.listCollections(); // 提取子集合名称,若无则设为null const subCollectionNames = subCollections.length > 0 ? subCollections.map(col => col.id) : null; return { id: doc.id, data: doc.data(), sub_collection: subCollectionNames }; }); // 等待所有异步任务完成,得到最终结果 const tempDoc = await Promise.all(docTasks); console.log(tempDoc); }).catch(error => { console.error("获取数据失败:", error); });
关键说明
doc.listCollections()是异步操作,必须用async/await或.then()处理结果- 用
map生成所有文档的异步任务数组,再通过Promise.all等待全部完成,避免嵌套回调 - 按示例要求,将子集合名称整理为数组,无则设为
null - 如果需要保留原代码中展开文档数据的格式(而非单独的
data字段),可以把返回对象改成{ id: doc.id, ...doc.data(), sub_collection: subCollectionNames }
内容的提问来源于stack exchange,提问作者Ever Loser
相关产品推荐
相关产品推荐

