首页 > 解决方案 > Firebase/javascript——如何将在firestore中创建的数据与用户连接起来

问题描述

Firebase v9

如何将在 Firestore 中创建的数据与创建此数据的用户连接起来?

我使用该createUserWithEmailAndPassword 功能在 firebase 中授权用户,授权后我使用 获取用户数据onAuthStateChanged,但是如何将特定用户与仅由他们创建的数据连接?

标签: javascriptreactjsfirebasefirebase-authentication

解决方案


例如,要为特定用户创建个人资料文档,常见的模式是使用用户的 UID 作为文档 ID。像这样的东西:

import { getAuth, onAuthStateChanged } from "firebase/auth";
import { doc, setDoc } from "firebase/firestore"; 

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
    const uid = user.uid;

    await setDoc(doc(db, "users", uid), {
      name: user.displayName
    });
    // ...
  }
});

另见:


推荐阅读