简体   繁体   English

如何从 Firestore 获取当前用户的文档?

[英]How can I get documents from Firestore for current user?

I'm trying do display data from Firestore database in my component.我正在尝试在我的组件中显示来自 Firestore 数据库的数据。

This is my function:这是我的 function:

const getData = async () => {
    const data = [];

    const querySnapshot = await getDocs(
      collection(databaseRef, "mK7DFNJgRAPmtvgrZh7X6AOj8cR2")
    );
    console.log(querySnapshot);
    querySnapshot.forEach((doc) => {
      console.log(doc.id, " => ", doc.data().Title);
      data.push({
        About: doc.data().About,
        Title: doc.data().Title,
        Who: doc.data().Who,
      });
    });
    setData(data);
  };

Collection ID = Current logged in User.集合 ID = 当前登录用户。 I want to display every document.我想显示每个文档。 Everything works fine but insteed of passing hard-coded string here:一切正常,但没有在这里传递硬编码的字符串:

      collection(databaseRef, "mK7DFNJgRAPmtvgrZh7X6AOj8cR2")

I would like to pass variable where I store my UID.我想在存储我的 UID 的位置传递变量。

Is there any way to do that?有没有办法做到这一点?

Assuming your user is logged in, you should be able to access their UID via firebase.auth().currentUser.uid .假设您的用户已登录,您应该能够通过firebase.auth().currentUser.uid访问他们的 UID。 This question 's answers may be useful for more information on getting the current user's ID. 这个问题的答案可能有助于获取有关获取当前用户 ID 的更多信息。

With that, you should be able to do:有了这个,你应该能够做到:

const querySnapshot = await getDocs(
    collection(databaseRef, firebase.auth().currentUser.uid)
);

to get the current user's documents.获取当前用户的文档。

https://firebase.google.com/docs/reference/js/v8/firebase.auth.Auth#currentuser https://firebase.google.com/docs/reference/js/v8/firebase.auth.Auth#currentuser

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM