'Multiple queries on Firestore CollectionReference and QuerySnapshot: cloud functions in node.js

Using Cloud Functions and node.js, I have a Firestore collection that I am querying and then selecting one random document from the returned documents. The problem is that I can't seem to query the QuerySnaphot that is returned from the initial query and I can't think of another way of going about it. For context, what I want to do is get the server time and minus 30 days from it, I then want to query the collection available-players for all player documents that have a timestamp of more than 30 days ago in the last_used field (which contains a timestamp) and then run some logic (that I know works independently so no need to show it all here).

      const availablePlayers = db.collection("available-players");
      const now = admin.firestore.Timestamp.now();
      const intervalInMillis = 30 * 24 * 60 * 60 * 1000;
      const cutoffTime = admin.firestore.Timestamp.fromMillis(now.toMillis() - intervalInMillis);

      const key = availablePlayers.doc().id;

      // query the last_used field
      const returnedPlayers = availablePlayers.where(last_used, "<=", cutoffTime);
      
      // this now doesn't work
      // it does work if I don't run the above query and just query availablePlayers
      returnedPlayers.where(admin.firestore.FieldPath.documentId(), '>=', key).limit(1).get()
      .then(snapshot => {
          if(snapshot.size > 0) {
            // do some stuff
                })
              });
          }
          else {
              const player = returnedPlayers.where(admin.firestore.FieldPath.documentId(), '<', key).limit(1).get()
              .then(snapshot => {
                  snapshot.forEach(doc => {
                    // do some stuff
                })
                  });
              })
              .catch(err => {
                  console.log('Error getting documents', err);
              });
          }
      })
      .catch(err => {
          console.log('Error getting documents', err);
      });

The idea is that I want to run the query, get the returned documents meeting the time criteria, generate a key from these, then use the key to select a random document. Is this because I am trying to query a QuerySnapshot, whereas just querying availablePlayers works because I'm querying a CollectionReference? How do I get around this? Any help would be greatly appreciated!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source