简体   繁体   中英

Cannot get all the document inside sub collection inside firestore

I have a collection name items, with document named after the uid and inside it there is another collection post which have autogenerated document and data. I am trying to query and get all the collection inside post.

<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 rules: Firestore 规则

I suspect that the query to the database runs before the u_id=user.uid line is every executed.

Since refreshing the user's authentication state may take some time, it is an asynchronous operation. Once that operation completes, your callback is executed and set the u_id variable. But by that time you've already queried the database with the wrong u_id value.

For this reason any code that needs the UID of the user, needs too be inside the callback that is executed when that UID is available.

So something like this:

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);
      });
    }
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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