1

I am looking at Firebase, cloud firestore and I am not understanding how I would perform a query and pass in an array.

const friendIds = [1, 2, 3];

Firestone.collection('conversations')
      .where('members', 'array-contains', friendIds)
      .get()
      .then(querySnapshot => console.log(querySnapshot))
      .catch(error => console.log(error));

anyone know how to achieve this?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
virtualLast
  • 573
  • 1
  • 5
  • 19

3 Answers3

2

This is currently not possible with a single query. array-contains can only find a single item in the named array.

Your alternative is to perform three queries, one for each item in the friendsId array, then merge the results in your code.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
0

Not sure if this is possible, but here's an example from the Firebase Node.js Snippets that can give you an idea:

  let citiesRef = db.collection('cities');

  // [START array_contains_filter]
  let westCoastCities = citiesRef.where('regions', 'array-contains',
    'west_coast');

  // [END array_contains_filter]

  westCoastCities.get()
    .then(res => {
      console.log('West Coast get: ', res);
    });

Reference Documentation

sllopis
  • 2,292
  • 1
  • 8
  • 13
0

According to the official documentation regarding query operators:

You can use the array-contains operator to filter based on array values.

As I can see in your code, your friendIds argument that is passed as the third parameter to the where() function is of type array. What you are actually doing, you are searching in the members property which is of type array for an array, which is actually not possible since I assume the members array in your database contains numbers.

An query like this:

Firestone.collection('conversations')
      .where('members', 'array-contains', 3)
      .get()
      .then(querySnapshot => console.log(querySnapshot))
      .catch(error => console.log(error));

Will work perfectly fine because we are searching within the members array for a number.

If you need to query for all those numbers, you should perform three separate queries and combine the result client side.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193