Use Cases

用 Claude Code 设计 Firestore:先从查询开始,而不是集合

使用 Claude Code 进行 Firestore query-first 设计:schema、索引、成本、安全规则与 TypeScript 示例。

Firestore 设计应该从查询开始

我是 Masa,运营 claudecode-lab.com。

我第一次使用 Firestore 时,也像设计关系型数据库一样先创建 userspostscomments。一开始看起来很清晰,但当页面需要“按发布时间列出文章”“按作者列出文章”“管理草稿”“按标签生成页面”时,这种 schema 很快就不够用了。

Firestore 不是一个可以依赖 JOIN 事后修正的数据模型。更安全的做法是先列出应用需要回答的问题,也就是查询,再设计文档结构。

官方参考:

claude -p "
为 CMS 设计 Firestore。
不要先提出 collection。
先按页面列出查询,并包含 where/orderBy/limit 和需要的 composite index。
"
export interface PostDoc {
  id: string;
  slug: string;
  title: string;
  status: "draft" | "published" | "archived";
  lang: "ja" | "en" | "es" | "ko";
  authorId: string;
  authorName: string;
  tagSlugs: string[];
  tagNames: string[];
  publishedAt: FirebaseFirestore.Timestamp | null;
  updatedAt: FirebaseFirestore.Timestamp;
}

authorName 这样的显示字段可以有意识地反规范化,以减少列表页的额外读取。索引也应该纳入 Git 管理:

{
  "indexes": [
    {
      "collectionGroup": "posts",
      "queryScope": "COLLECTION",
      "fields": [
        { "fieldPath": "lang", "order": "ASCENDING" },
        { "fieldPath": "status", "order": "ASCENDING" },
        { "fieldPath": "publishedAt", "order": "DESCENDING" }
      ]
    }
  ]
}

我把这个流程应用到文章、联系表单和日志设计时,重写了初稿的一半以上。最大的收益是:先让 Claude Code 产出查询表和索引表,再写代码。

#claude-code #gcp #firestore #database #typescript #query-design
免费

免费 PDF:5 分钟看懂 Claude Code 速查表

只需留下邮箱,我们就会立即把这份 A4 一页速查表 PDF 发送给你。

我们会严格保护你的个人信息,绝不发送垃圾邮件。

让你的 Claude Code 工作流更上一层楼

50 个经过实战检验的提示词模板,现在就能复制粘贴到 Claude Code 中使用。

Masa

本文作者

Masa

深度使用 Claude Code 的工程师。运营 claudecode-lab.com——一个涵盖 10 种语言、超过 2,000 页内容的科技媒体。