Home > Net >  Complex compound queries in firebase V9
Complex compound queries in firebase V9

Time:10-18

I started work with Firebase new web v9 modular version. And for filtering result I need to use compound queries. I have three inputs:

  1. First name
  2. Last name
  3. Type

When I filtering result I make request not always by three queries, sometimes I use one or two queries by request, so I don't know how mane queries I have to made, it always is different.

To solve this in web v8 namespased version I made this code:

const [firstName, setFirstName] = useState('')
const [lastName, setLastName] = useState('')
const [type, setType] = useState('')


const filterRezult = () => {
   let filterQuety = db.collection('users')

   if(firstName !== ''){
      filterQuety = filterQuety.where('data.first_name', '==', firstName)
   }

   if(lastName !== ''){
      filterQuety = filterQuety.where('data.last_name', '==', lastName)
   }

   if(type !== ''){
      filterQuety = filterQuety.where('data.type', '==', type)
   }

   await filterQuety.get().then((result) => {
      ...
   })
}

And it works very well. Any suggestions how to do same thing in web v9 modular version?

CodePudding user response:

I find out a solution of this situation.

So since all fields are non empty strings in database, I can use Not equal (!=) operator in conditional statement. If my state not equal to empty string, then I make a query by required condition, if state is empty string then I make query of all documents that contains non empty string data.

It should look something like that

const [firstName, setFirstName] = useState('')
const [lastName, setLastName] = useState('')
const [type, setType] = useState('')

const filterRezult = async () => {
   const searchRef = collection(db, 'users')
   const querySearch = query(searchRef,
   (firstName !== ''
      ? where('data.first_name', '==', firstName)
      : where('data.first_name', '!=', firstName)
   ),
   (lastName !== ''
      ? where('data.last_name', '==', lastName)
      : where('data.last_name', '!=', lastName)
   ),
   (type !== ''
      ? where('data.type', '==', type)
      : where('data.type', '!=', type)
   }

   await getDocs(querySearch)
    .then((result) => {
       ...
    })
    .catch((error) => {
      ...
   })
}

I don't know is it best solution, but it works in my case pretty well

CodePudding user response:

That'd be:

const conditions = []

if(firstName !== ''){
   conditions.push(where('data.first_name', '==', firstName))
}

if(lastName !== ''){
   conditions.push(where('data.last_name', '==', lastName))
}

if(type !== ''){
   conditions.push(where('data.type', '==', type))
}

const filterQuery = query(collection(db, 'users'), conditions)
const result = await getDocs(filterQuery)

I highly recommend keeping the documentation and upgrade guide handy during this type of exercise.

  • Related