0

I'm trying to query an array of objects from my firestore database, I've tried many methods such as array-contains, array-contains-any, in, but to no avail.

I have a users array, and it's an array of objects, each object has two properties-- id and role. I want to write a query that will selectively get a document in which the current logged in user is present in the user's array.

db.collection('chatRooms')
            .where(/* What am I supposed to do here */)
            .get()
            .then((snapshot) => {
                setRooms(
                    snapshot.docs.map((room) => {
                        return { id: room.id, data: room.data() };
                    })
                );
            });

Here's a snapshot of how I'm storing the data:

Here's a snapshot of how I'm storing the data

kunalkeshan
  • 13
  • 1
  • 5

1 Answers1

0

To use array-contains on an array of objects, you must know the entire object. It seems feasible in this case if you know UID of current user and role as well. Try running the following query:

const userId = firebase.auth().currentUser.uid

db.collection('chatRooms')
  .where('users', 'array-contains', { id: userId, role: 'Admin' })
  .get()
  .then((snapshot) => {
    setRooms(
      snapshot.docs.map((room) => {
        return { id: room.id, data: room.data() };
      })
    );
});

The above query will return documents where users array contains current user's UID with 'Admin' role only! There's currently no way to query based on a single field in array of object.

If you don't know user's role then you might have to store users as a sub-collection instead of array.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84