You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用NodeJS SDK获取Firestore所有带子集合的集合数据

Firestore 获取所有国家及下属城市的Node.js实现

Firestore 原生不支持跨嵌套集合的关联查询,要得到你需要的结构化返回结果,按以下逻辑实现即可:

  • 第一步:查询根集合countries下的所有国家文档
  • 第二步:遍历所有国家文档,并发查询每个文档下的cities子集合,将国家数据、对应城市数据组装为目标结构

可直接运行的代码示例

const { getFirestore } = require('firebase-admin/firestore');
const db = getFirestore();

async function getCountriesWithCities() {
  // 拉取全量国家文档,可按需添加where过滤条件,比如只查启用的国家
  const countriesSnap = await db.collection('countries')
    // 示例过滤:.where('isEnable', '==', true)
    .get();

  // 并发查询每个国家对应的城市集合
  const taskList = countriesSnap.docs.map(async (countryDoc) => {
    const country = {
      id: countryDoc.id,
      ...countryDoc.data()
    };

    const citiesSnap = await countryDoc.ref.collection('cities')
      // 示例过滤:.where('isEnable', '==', true)
      .get();
    
    const cities = citiesSnap.docs.map(cityDoc => ({
      id: cityDoc.id,
      ...cityDoc.data()
    }));

    return { country, cities };
  });

  return Promise.all(taskList);
}

// 调用示例
getCountriesWithCities()
  .then(result => {
    // result 就是你需要的结构数组
    console.log(result);
  })
  .catch(err => {
    console.error('查询出错:', err);
  });

注意事项

  • 该方案会产生1 + N次查询(1次查所有国家,N次查N个国家对应的城市集合),如果国家总量很大,建议给国家查询加分页,避免一次性发起过多并发请求
  • 如果你需要频繁查询该类关联数据,可以考虑在写入城市数据时,将关联的城市信息冗余存储到国家文档中,用空间换查询效率,减少查询次数

内容的提问来源于stack exchange,提问作者Amirhosein Rajabi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 20:36:33