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

Firebase v9中如何将Firestore创建的数据与对应用户关联

实现Firebase用户与其创建的Firestore数据关联的方案

核心逻辑是用Firebase Auth返回的用户唯一标识uid作为关联锚点,贯穿数据写入、权限校验、查询三个环节:

1. 写入数据时嵌入用户uid

onAuthStateChanged返回的登录用户对象中包含全局唯一的uid字段,所有用户创建的文档写入Firestore时,必须携带该字段作为关联标记:

import { getAuth, onAuthStateChanged } from "firebase/auth";
import { getFirestore, collection, addDoc } from "firebase/firestore";

const auth = getAuth();
const db = getFirestore();

// 监听登录状态
onAuthStateChanged(auth, async (user) => {
  if (user) {
    // 写入数据时新增authorUid字段绑定当前用户
    await addDoc(collection(db, "userCreatedData"), {
      content: "用户自定义内容",
      createTime: new Date(),
      authorUid: user.uid // 核心关联字段
    })
  }
})

2. 配置Firestore安全规则防止越权

仅在文档中存uid无法避免其他用户恶意访问,需要配置安全规则限制仅本人可读写自己的数据:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /userCreatedData/{docId} {
      // 读权限:仅文档关联的用户本人可访问
      allow read: if request.auth != null && request.auth.uid == resource.data.authorUid;
      // 写权限:仅允许写入本人uid作为关联字段的文档
      allow write: if request.auth != null && request.auth.uid == request.resource.data.authorUid;
    }
  }
}

3. 查询时用uid过滤获取专属数据

需要拉取用户自己创建的数据时,直接用uid作为查询条件过滤即可:

import { getAuth, onAuthStateChanged } from "firebase/auth";
import { getFirestore, collection, query, where, getDocs } from "firebase/firestore";

const auth = getAuth();
const db = getFirestore();

onAuthStateChanged(auth, async (user) => {
  if (user) {
    // 构造带uid过滤的查询条件
    const userDataQuery = query(
      collection(db, "userCreatedData"),
      where("authorUid", "==", user.uid)
    )
    const querySnapshot = await getDocs(userDataQuery);
    // 处理返回的当前用户专属数据
    const myDataList = querySnapshot.docs.map(doc => ({id: doc.id, ...doc.data()}))
  }
})

可选优化方案:如果业务数据量较大,可直接用用户uid作为子集合的父级文档ID,比如数据路径设为/users/{uid}/customData/{docId},这种结构下安全规则和查询不需要额外增加字段过滤,逻辑更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 15:06:06