Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

511
Views
How to Query within an array of object in Firestore?

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!