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?

2
  • I think you can use Javascript eval function and array join function. Commented Jan 13, 2020 at 2: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 explains how to do that (disclaimer, I'm the author). Commented Jan 13, 2020 at 16:03

2 Answers 2

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'

Sign up to request clarification or add additional context in comments.

2 Comments

will this return a query which contains ALL the cases ? I want the documents where all cases match.
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: stackoverflow.com/questions/52837711/…
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(''))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.