0

I'm building an app using React + Redux + Firebase. In Firestore users collection, I have multiple fields including language, subject as map data. So for example,

// language that user can speak
language = {
  english: true
}
// subjects that the user can teach
subject = {
  math: true
  science: true
}

In the main app, user can search other users by filtering subjects and languages. For example, user may look for the other users who can teach 'math' and 'science' using an 'english' language.

And I'm struggling with filtering multiple fields in map data. I could query for on field by doing ref.where('subject.${val}', '==' , true). But is there any way to query on multiple fields to get a document which contains a subject hash at any given number of subjects?

I tried to put data in array but currently firebase Array membership only support filtering one item in the array. So I guess it's a good start with storing in hash map. Any suggestion?

ykdojo
  • 45
  • 1
  • 5

1 Answers1

2

I tried to put data in array but currently firebase Array membership only support filtering one item in the array.

You're right, you can filter your items only by a single item that exist in an array. If you'll chain more than one function call, you'll get an error similar with this:

Invalid Query. Queries only support having a single array-contains filter.

And to answer your question:

But is there any way to query on multiple fields to get a document which contains a subject hash at any given number of subjects?

Unfortunately, there are no wildcards in Firestore. You have to identify the property names of your documents by their exact property name.

If you want to limit the results by filtering on multiple properties, you need to chain where() functions, like in the following example:

ref.where('subject.math', '==' , true)
    .where('subject.science', '==' , true)
    .where('language.english', '==' , true)
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Thanks @Alex Mamo :) – ykdojo Jan 23 '19 at 20:19
  • @Alex Mamo, how would you do this type of chaining dynamically? Let's say I don't know how many subjects or languages I need to query against until I receive them. – katyusha Mar 23 '20 at 21:37
  • @katyusha I'm afraid I didn't understand your question. Can you please elaborate as a new question here on StackOverflow, using its own [MCVE](https://stackoverflow.com/help/mcve), so I and other Firebase developers can help you. – Alex Mamo Mar 24 '20 at 10:13
  • @Alex Mamo, sure thing. Just posted a new question here: https://stackoverflow.com/questions/60832639/how-to-build-a-firestore-query-chain-based-on-a-dynamic-response-from-a-promise – katyusha Mar 24 '20 at 14:03
  • I am using firestore. How can we use where conditions in this situation - fetch all the chat conversations where "(senderid == loggedinuserid and receiverid == 10) or (senderid == 10 and receiverid == loggedinuserid)"? kindly suggest. Thanks. – Kamlesh Jun 15 '21 at 20:05