【问题标题】:Cannot get all the document inside sub collection inside firestore无法获取firestore内子集合中的所有文档
【发布时间】:2021-05-24 06:37:17
【问题描述】:

我有一个集合名称项目,文档以 uid 命名,其中有另一个集合帖子,其中包含自动生成的文档和数据。我正在尝试查询并获取帖子中的所有集合。

<pre>

    <script>
      function show_items(){
       var u_id;
        firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        u_id=user.uid;
        console.log(u_id);
      } else {
        return;
      }
    });
        var outputlist=[];
        var dbs=firebase.firestore();
        dbs.collection('items').doc(u_id).collection('post').get().
        then(querySnapshot => {
          console.log(querySnapshot.size);
         if (querySnapshot.empty) {
           console.log('No matching documents.');
         }
          querySnapshot.forEach(doc => {
            console.log(doc.id, '=>',doc.data());
            outputList.push(doc.data());
          });
        })
          .catch(err => {
          console.log('Error getting documents', err);
        });
      }
    </script>

</pre>

Firestore 规则:

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    我怀疑对数据库的查询在每次执行 u_id=user.uid 行之前运行。

    由于刷新用户的认证状态可能需要一些时间,所以它是一个异步操作。该操作完成后,将执行您的回调并设置 u_id 变量。但是到那时你已经用错误的u_id 值查询了数据库。

    因此,任何需要用户 UID 的代码也需要在该 UID 可用时执行的回调中。

    所以是这样的:

    function show_items(){
      firebase.auth().onAuthStateChanged(function(user) {
        if (user) {
          var outputlist=[];
          var dbs=firebase.firestore();
          dbs.collection('items').doc(user.uid).collection('post').get().
          then(querySnapshot => {
            console.log(querySnapshot.size);
            if (querySnapshot.empty) {
              console.log('No matching documents.');
            }
            querySnapshot.forEach(doc => {
              console.log(doc.id, '=>',doc.data());
              outputList.push(doc.data());
            });
          }).catch(err => {
            console.log('Error getting documents', err);
          });
        }
      });
    }
    

    【讨论】:

    • 谢谢,坦率地说它帮助了我。我在登录时将 uid 存储在会话存储中。
    猜你喜欢
    • 2018-04-03
    • 2020-02-27
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    相关资源
    最近更新 更多