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?

0

3 Answers 3

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.

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

1 Comment

is this still the case in 2023?
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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.