skip to Main Content

How can I adjust the Firebase query expression below to accommodate missing query parameters?

admin.firestore().collection('vehicles').where('type', '==', request.query['car'])

The expression above works when ?car=ford is passed as part of the GET request. I would like to use something like the following whenever the query parameter is not passed:

admin.firestore().collection('vehicles').where('type', '==', [request.query['car'] || ***the current vehicle type***])

Do you have any suggestions?

2

Answers


  1. Chosen as BEST ANSWER

    Ok, since

    admin.firestore().collection('vehicles').where('type', '==', [request.query['car'] || ***the current vehicle type***])
    

    will not work when a query parameter is not part of the API call, the solution is to filter after the collection is obtained. The following works:

    admin.firestore().collection('vehicles').get()
       .then(results => {
          let tempDoc = results.docs.map((doc) => {
             return { id: doc.id, ...doc.data()}
          });
          if(!!request.query['type']){
             tempDoc = tempDoc.filter((x:any) => x['type'] === request.query['type']);
          }
    });
    

    The bottom line: the .where clause is insufficient to handle filtering for when a query parameter is passed and for when a query parameter is not passed.


  2. If I correctly understand, the "current vehicle type" is somehow known in your front end (e.g. you have it in a variable or in a field) or in your server side or Cloud Function code (you use the Admin SDK).

    If this is the case, you just have to calculate the desired value for the third argument of the where() method before using it. Something along the following lines:

    function isNullOrUndefined(value) {
       return value === undefined || value === null;
    }
    
    const currentVehicleType = ...; 
    const filterValue = isNullOrUndefined(request.query['car']) ? currentVehicleType : request.query['car'];
    const q = admin.firestore().collection('vehicles').where('type', '==', filterValue);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search