0

I do have this structure:

db.collection('users')

and want to make this:

db.collection('users')
   .where('works', 'array-contains', 'CASE_A')
   .where('works', 'array-contains', 'CASE_B')
   .where('works', 'array-contains', 'CASE_C')
   ...

In this case, I will make an array of
(( .where('works', 'array-contains',${variable}))

and i will add this in the beginning db.collection('users'), how can i make this?

Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
eeerrrttt
  • 549
  • 2
  • 7
  • 24
  • I think you can use Javascript eval function and array join function. – TopW3 Jan 13 '20 at 02:21
  • If you want to write a query which contains ALL the cases, you will have to create a separate query for each case and merge the query results in your app. The following [article](https://medium.com/firebase-tips-tricks/how-to-combined-two-firestore-queries-to-simulate-a-logical-or-query-27d28a43cb2d) explains how to do that (disclaimer, I'm the author). – Renaud Tarnec Jan 13 '20 at 16:03

2 Answers2

2

Just make an inline array:

db.collection('users')
   .where('works', 'array-contains', ['CASE_A', 'CASE_B', 'CASE_C'])

Or use a variable if you want:

const array = ['CASE_A', 'CASE_B', 'CASE_C']
db.collection('users')
   .where('works', 'array-contains', array)

If you actually want to find documents where all cases are present (not where any of the cases are present), you won't be able to use an array-contains type query. You will have to convert your array into an object and query it as shown in this question: Firestore: Multiple 'array-contains'

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • will this return a query which contains ALL the cases ? I want the documents where all cases match. – eeerrrttt Jan 13 '20 at 02:53
  • 1
    No, this will do a logical OR of each item. You can't do a logical AND of each item, as Firestore doesn't support multiple array-contains clauses in a single query. If you want to use an object instead of an array, use this: https://stackoverflow.com/questions/52837711/firestore-multiple-array-contains – Doug Stevenson Jan 13 '20 at 02:56
1

Please try this code.

const makeItem = value => `.where('works', 'array-contains',${value}`

const arrFuncs = [
    makeItem('CASE_A'),
    makeItem('CASE_B'),
    makeItem('CASE_C'),
]

const initialCmd = `db.collection('users')`
eval(initialCmd + arrFuncs.join(''))
TopW3
  • 1,477
  • 1
  • 8
  • 14