Firestore: Multiple 'array-contains'

Issue

Update on this question

Firestore launched another feature similar to the in query, the array-contains-any query. This feature allows you to perform array-contains queries against multiple values at the same time.

Use the array-contains-any operator to combine up to 10 array-contains clauses on the same field with a logical OR. An array-contains-any query returns documents where the given field is an array that contains one or more of the comparison values:

ref = ref.where('node_sku' , 'array-contains-any' , list);

Firestore – Array contains any

Question

I am trying to filter data with multiple where() methods using the array-contains operator, however I am having the following error:

An error occured: Error: 3 INVALID_ARGUMENT: 
A maximum of 1 'ARRAY_CONTAINS' filter is allowed.

Basically, I have a collection containing the following docs:

product1 
  - node_sku ['sku1', 'sku2', 'sku3' ]

product2 
  - node_sku ['sku4', 'sku5', 'sku6' ]

Then I have my array with items I wish to find on the database:

const list = ['sku4', 'sku2']

I want to search for sku4 and sku2, if finds any returns the object.

My problem is that array-contains is not allowed to run more than once.

Here’s the code I am using to filter:

const list = ['sku4', 'sku2'];


let database = firestore_db.collection('glasses');
let ref = database;

list.forEach( (val) => { 
    ref = ref.where('node_sku' , 'array-contains' , val);
});
ref.get() 
.then( (snapshot) => glassesRequestComplete(snapshot, req, response))
.catch( (error) => glassesRequestError(error, response) );

As you notice, my problem is that I am looping through my list array, however my ref is throwing an error since I am firing ‘array-contains’ more than once.

I have also tried to compare against the array:

ref.where('node_sku' , 'array-contains' , list);

which does not return any , I believe array-contains does not compare against arrays, only strings/numbers/booleans maybe?

Does anybody know a solution for that without having to query them individually?

Thank you

Solution

Firestore launched another feature similar to the in query, the array-contains-any query. This feature allows you to perform array-contains queries against multiple values at the same time.

ref = ref.where('node_sku' , 'array-contains-any' , list);

Firestore – Array contains any

Answered By – Dan Philip

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published