0

I have an array of sports I want to query cloud firestore with, but the array can differ in size. Sometimes there will be a query for 1 sport, other times two sports, and etc. It would be like array-contains, but reversed. I have an array and I want to see if any of those items are in the database. I know I can chain .where(), but how would I dynamically change that according to the number of items in the array?

How would I go about implementing that in the Firestore query? Would I map the array of sports into where(sport '==' SPORT_NAME_HERE)?

Here's what the query would look like for a single sport (string):

let sportsQuery = await database.collection('sports')
                        .where('sport', '==', 'SPORT_NAME_HERE')
                        .orderBy('sport_team')
                        .limit(7)

Here's what I was thinking along the lines of. Totally not sure if a .then is even allowed, but that was my solution so far: let sports = ['golf', 'tennis', 'basketball'];

 let sportsQuery = await database.collection('sports')
     .then(
       sports.map(sport => {
         .where('sport', '==', `${sport}`)
       })
     )
     .orderBy('sport_team')
     .limit(7)
Jeff Lewis
  • 65
  • 1
  • 7

1 Answers1

1

You should combine several queries along the following lines. Since we want to execute a variable number of queries in parallel, we use Promise.all().

  var database = firebase.firestore();

  const sports = ['golf', 'tennis', 'basketball'];

  const promises = [];

  sports.forEach(function(element) {
    const sportsQuery = database
      .collection('sports')
      .where('sport', '==', element)
      .orderBy('sport_team')
      .limit(7)
      .get();

    promises.push(sportsQuery);
  });

  Promise.all(promises).then(function(results) {
    //results is an array of QuerySnapshots, since the get() method returns a QuerySnapshot
    results.forEach(function(querySnapshot) {
      querySnapshot.forEach(function(doc) {
        console.log(doc.id, ' => ', doc.data());
        //It's up to you to possibly populate an array here, that you may sort later on
      });
    });
  });
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121