4

Firestore query criteria Firestore query criteria Console.log of the query result Console.log of the query result Source code-render data Source code-render data I am new to react native firebase firestore. I am designing an app where the functionality is that the user should be able to search for a registered user on any of the three critieria:

  1. by Name

  2. by Expertise

  3. by Location

If the user explicitly types in these fields, my code will retrieve the filtered result from firestore

Code in react native to retrieve from firestore:

var db = firebase.firestore();
    var routeRef = db.collection("users");
    var queryResult = routeRef
.where(("Name", "==", NameInput)
.where("Expertise", "==", ExpertiseInput)
.where("Location","==" , LocationInput))
.get().then(function(snapshot){/* ... */}

Scenario: If the user did not type in any search criteria in the UI for any one field, say "Location" , in that scenario I dont want to set the filter for that criteria from firestore. That means , the expected code should be:

   var queryResult = routeRef
    .where(("Name", "==", NameInput)
    .where("Expertise", "==", ExpertiseInput)

Question: I am not sure how to dynamically set the .where condition based on the whether user typed in UI or not. Can anyone please help?

Still this does not get the query result

Bhol
  • 145
  • 3
  • 16

1 Answers1

8

The where() function returns a Query object (which allows you to query multiple where() conditions in the first place). So you can sorta "save the step-by-step progress" conditionally. Something like this:

const routeRef = db.collection("users");
const nameFilter = NameInput ? routeRef.where("Name", "==", NameInput) : routeRef;
const expertiseFilter = ExpertiseInput ? nameFilter.where("Expertise", "==", ExpertiseInput) : nameFilter;
const locationFilter = LocationInput ? expertiseFilter.where("Location", "==", LocationInput) : expertiseFilter;
locationFilter.get().then(snapshot => {
   // The snapshot returned by `where().get()` does not have a `data()` reference since it returns multiple documents, it has `docs` property which is an array of all the documents matched
   snapshot.docs.forEach(doc => {
     const docData = { ...doc.data(), id: doc.id };
     console.log(docData);
})
JayCodist
  • 2,424
  • 2
  • 12
  • 28