Firebase 最常被一起提到的数据库,是 Cloud Firestore。
你可以把它理解成:
商圈里的主账本系统。
这本账本的特点不是“像传统 SQL 那样一行行表格”,而是:
- 数据按 document / collection 组织
- 天然适合客户端直接读写
- 支持实时监听
- 支持离线缓存
- 有安全规则
- 能和 Auth / Functions 深度联动
官方文档对 Firestore 的核心卖点非常明确:
- flexible
- scalable
- realtime
- offline support
- designed to scale
先看一个最小写入示例:
import { initializeApp } from "firebase/app";
import {
getFirestore,
collection,
addDoc,
serverTimestamp
} from "firebase/firestore";
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
export async function createShopOrder() {
const docRef = await addDoc(collection(db, "orders"), {
userId: "u_001",
productName: "机械键盘",
status: "pending",
createdAt: serverTimestamp(),
});
console.log("订单创建成功:", docRef.id);
}读取和实时监听:
import {
getFirestore,
collection,
query,
where,
onSnapshot
} from "firebase/firestore";
const db = getFirestore(app);
const q = query(
collection(db, "orders"),
where("status", "==", "pending")
);
const unsubscribe = onSnapshot(q, (snapshot) => {
const orders = snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
console.log("待处理订单实时变化:", orders);
});你可以把它理解成:
商铺账本不是每天晚上统一抄一次
而是账本一有变动,相关柜台立刻收到通知#Firestore 的数据心智
collection = 某类账本区域
document = 单条业务记录
field = 记录里的字段
subcollection = 某条记录下面继续挂子账本例如:
shops/
shop_001
name: "北区旗舰店"
orders/
order_001
order_002#Firestore 为什么适合很多现代应用
因为它特别贴合这些场景:
- 任务列表
- 协作工具
- 聊天和动态流
- 控制台和后台
- 移动端业务数据
- 需要实时刷新的产品
但你也要记住:
Firestore 是 NoSQL 文档数据库,不是“云上万能关系库”。
如果你脑子里始终是:
- 多表 join
- 复杂事务主导
- 强关系报表分析
那你很容易把账本建得很痛苦。