You need to enable JavaScript to run this app. 同GCP项目下如何配置Cloud Function访问Firestore并实现CRUD操作?
优惠活动
大模型
产品
解决方案
定价
更多

同GCP项目下如何配置Cloud Function访问Firestore并实现CRUD操作?

前期准备
  • 确认GCP项目已开启Cloud Functions、Cloud Build、Firestore API
  • 本地开发需安装gcloud CLI并完成授权、切换到目标项目,也可以直接使用GCP控制台内置的在线编辑器开发,无需本地环境
  • 同项目下的Cloud Functions默认关联的服务账号已拥有Firestore读写权限,无需额外配置密钥,SDK会自动读取运行环境的项目身份信息
Cloud Functions 定义说明(Node.js 运行时)

推荐使用2代Cloud Functions,性能和扩展性优于1代。你可以选择HTTP触发器(供你的Web应用直接调用),也可以根据需求选择Firestore触发器(当Firestore数据变更时自动触发函数逻辑),以下示例以通用的HTTP触发器为例。

Node.js 访问Firestore CRUD 完整示例

依赖配置

在项目package.json中添加以下依赖:

{
  "dependencies": {
    "@google-cloud/firestore": "^7.7.0",
    "@google-cloud/functions-framework": "^3.4.0"
  }
}

业务代码(index.js)

const functions = require('@google-cloud/functions-framework');
const { Firestore } = require('@google-cloud/firestore');

// 同项目下无需传入额外配置,SDK自动获取环境中的项目信息
const db = new Firestore();
// 替换为你自己的Firestore集合名
const TARGET_COLLECTION = 'your_collection_name';

// 定义HTTP触发的CRUD函数
functions.http('firestoreCrudHandler', async (req, res) => {
  // 允许跨域配置,供你的前端Web应用调用,不需要可删除
  res.set('Access-Control-Allow-Origin', '*');
  res.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.set('Access-Control-Allow-Headers', 'Content-Type');

  if (req.method === 'OPTIONS') {
    return res.status(204).send('');
  }

  try {
    switch (req.method) {
      // 新增文档(Create)
      case 'POST': {
        const insertData = req.body;
        const docRef = await db.collection(TARGET_COLLECTION).add(insertData);
        return res.status(201).json({
          id: docRef.id,
          ...insertData
        });
      }
      // 查询文档(Read)
      case 'GET': {
        const docId = req.query.docId;
        // 传docId查单个文档,不传查全量
        if (docId) {
          const docSnapshot = await db.collection(TARGET_COLLECTION).doc(docId).get();
          if (!docSnapshot.exists) {
            return res.status(404).json({ error: '文档不存在' });
          }
          return res.status(200).json({
            id: docSnapshot.id,
            ...docSnapshot.data()
          });
        } else {
          const collectionSnapshot = await db.collection(TARGET_COLLECTION).get();
          const docList = collectionSnapshot.docs.map(doc => ({
            id: doc.id,
            ...doc.data()
          }));
          return res.status(200).json(docList);
        }
      }
      // 更新文档(Update)
      case 'PUT': {
        const docId = req.query.docId;
        if (!docId) {
          return res.status(400).json({ error: '缺少docId参数' });
        }
        const updateData = req.body;
        await db.collection(TARGET_COLLECTION).doc(docId).update(updateData);
        return res.status(200).json({ message: '更新成功' });
      }
      // 删除文档(Delete)
      case 'DELETE': {
        const docId = req.query.docId;
        if (!docId) {
          return res.status(400).json({ error: '缺少docId参数' });
        }
        await db.collection(TARGET_COLLECTION).doc(docId).delete();
        return res.status(200).json({ message: '删除成功' });
      }
      default:
        return res.status(405).json({ error: '不支持的请求方法' });
    }
  } catch (err) {
    console.error('操作异常:', err);
    return res.status(500).json({ error: '服务内部错误' });
  }
});
部署方法
  • 本地部署:在代码根目录执行以下命令,将your_region替换为你使用的GCP区域,不需要公开访问可删除--allow-unauthenticated参数
gcloud functions deploy firestoreCrudHandler --runtime nodejs20 --trigger-http --allow-unauthenticated --region your_region --gen2
  • 控制台部署:直接在GCP Cloud Functions页面创建新函数,运行时选择Node.js 20,将上述代码粘贴到在线编辑器,依赖会自动安装
注意事项
  • 上述示例适配Firestore原生模式,若使用Datastore模式需要调整SDK配置
  • 生产环境请关闭--allow-unauthenticated,按需配置IAM权限控制函数访问范围
  • 操作子集合时,将集合路径替换为父集合/{父文档ID}/子集合即可

内容的提问来源于stack exchange,提问作者Edward James Smith II

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 03:54:03