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

如何使用Javascript调用REST API向Firestore数据库新增文档

纯JavaScript调用Firestore REST API创建文档并绑定按钮点击事件示例

前置准备

  • 提前替换示例中占位的Firestore项目ID、集合名、请求体字段,和你Postman调试通过的参数保持一致
  • 若你的Firestore规则需要身份认证,提前准备好有效的用户认证令牌

完整示例代码

<!-- 页面按钮 -->
<button id="createFirestoreDocBtn">创建Firestore文档</button>
<p id="operationTip"></p>

<script>
// 绑定按钮点击事件
document.getElementById('createFirestoreDocBtn').addEventListener('click', async () => {
  const tipDom = document.getElementById('operationTip');
  tipDom.textContent = '请求处理中...';

  // 替换为你自己的项目参数
  const PROJECT_ID = '你的Firestore项目ID';
  const COLLECTION = '目标集合名';
  const API_URL = `https://firestore.googleapis.com/v1/projects/${PROJECT_ID}/databases/(default)/documents/${COLLECTION}`;

  // 替换为Postman调试通过的请求体,严格遵循Firestore字段类型格式
  const postData = {
    fields: {
      // 示例字段,按实际需求修改
      name: { stringValue: '测试数据' },
      count: { integerValue: 100 },
      is_valid: { booleanValue: true }
    }
  };

  try {
    const res = await fetch(API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        // 需要认证时打开下方注释,替换为实际令牌
        // 'Authorization': 'Bearer 你的用户认证令牌'
      },
      body: JSON.stringify(postData)
    });

    if (!res.ok) throw new Error(`请求错误:${res.status}`);
    const result = await res.json();
    const docId = result.name.split('/').pop();
    tipDom.textContent = `创建成功,文档ID:${docId}`;
    console.log('返回结果', result);
  } catch (err) {
    tipDom.textContent = `创建失败:${err.message}`;
    console.error(err);
  }
});
</script>

关键说明

  • Firestore REST API要求请求体必须嵌套在fields字段下,每个值要指定对应类型:字符串对应stringValue、整数对应integerValue、布尔值对应booleanValue、浮点数对应doubleValue、时间戳对应timestampValue
  • 若要更新指定文档,将请求方法改为PATCH,API地址末尾拼接上要修改的文档ID即可
  • 如果你项目中使用axios等请求库,只需替换fetch部分的逻辑,请求头、请求体参数保持不变即可
  • 生产环境务必配置Firestore安全规则,禁止开放公开读写权限,避免数据泄露或被恶意篡改

内容的提问来源于stack exchange,提问作者Ian Barber

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 19:12:02