【问题标题】:Firebase, web application: get documents by userFirebase,网络应用程序:按用户获取文档
【发布时间】:2025-12-27 08:40:11
【问题描述】:

我正在我的网络项目上尝试 Firebase,我想知道如何通过当前登录的用户从 Firestore 获取数据。

我正在尝试这样的事情:

import firebase from 'firebase';

const uid = firebase.auth().currentUser.uid;
firebase.firestore().collection('posts').add({
        title: this.title,
        content: this.content,
        user: uid
})
firebase.firestore().collection('posts').where("user", "==", uid).get()
    .then(snapshots => {
      this.posts = snapshots.docs.map(doc => {
        const data = doc.data();
        return {
          id: doc.id,
          title: data.title,
          content: data.content
        }
      })
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error.message);
    });

什么效果好,但看起来不是很“专业”,所以我只是想知道是否有任何适当的方法可以做到这一点。

【问题讨论】:

    标签: javascript firebase google-cloud-firestore firebase-authentication


    【解决方案1】:

    如下图使用isEqualTo:

    where("user", isEqualTo: uid).get()

    【讨论】:

      【解决方案2】:

      IMO,您的代码看起来不错且可读 - 如果这等于花哨,请不要试图成为“专业”。下面的观点只是一个人对更多地使用变量的看法:)

      const db = firebase         
          .initializeApp({ 
              // config ...
          }) 
          .firestore();
      
      const auth = firebase.auth();
      const user = auth.currentUser.uid;
      
      const postRef = db.collection('posts');
      
      //  add 
      const { title, content } = this;
      postRef
          .add({
              title,
              content,
              user
          })
      
      //  get 
      postRef
          .where('user', '==', user)
          .get()
          .then(snapshot => {
              this.posts = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }))  
          })
          .catch(console.error)
      

      【讨论】:

      • 我假设你喜欢所有的帖子数据 + ID