1

So this is the situation.

I have a database which has a Users collection. In some users I have a userType property, but some users don't have this property. userType can be equal to both person and company. How can I pick only the users that have the userType property? I could do something like this:

let persons = await admin.database().ref('Users').orderByChild('userType').equalTo('person').once('value');
persons = await persons.val();

let companys = await admin.database().ref('Users').orderByChild('userType').equalTo('company').once('value');
companys = await companys.val();

let users = persons + companys;

but this is just ugly. How can I filter this using a firebase query?

I found this answer Query based on multiple where clauses in Firebase but it's from 2014, so I hoped that maybe some improvement was made in 4 years.

Alex Ironside
  • 4,658
  • 11
  • 59
  • 119
  • The answer you found it still correct. You will have to ensure that each user has a value for the `userType` property, since Firebase can't filter for the absence of a property. For example, use a value `none` for the users without a type. Then you can combine the two values you want to filter on into a single property `"company_userType": "company_person"` and filter on that as shown in my linked answer. – Frank van Puffelen Sep 20 '18 at 13:34

1 Answers1

0

The improvement that's been made is the release of Cloud Firestore as an alternative to the Realtime Database. Firestore supports a range of simple and compound queries in a more logical way.

usersRef.whereEqualTo("userType", "person").whereEqualTo("userType", "company")

That being said performing an OR query still requires you to merge the two results like you have done above.

If that doesn't work for you it may be worth looking at a search indexer like Algolia, as recommended by Firebase.

Chris Edgington
  • 2,937
  • 5
  • 23
  • 42
  • I cannot switch to firestore, I have to user the realtime database – Alex Ironside Sep 20 '18 at 11:35
  • 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:01