Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

firebase how to query through array of objects

I need to write a query for Firestore which will filter records based on id in the array, so I have a collection of "assignments" and each assignment has records more or less like this:

{
"name" :"abc",
"status": "accepted",
"assignedAt": "timestamp",
"createdAt": "timestamp",
"recipients": [
  {
   id: "123",
   name: "recipient1"
  },
 {
   id: "456",
   name: "recipient2"
  }
]
}

I wish to write a query that will check if user.id exists as an id in the recipients array, except that I also filter out some statuses but this part works, so far I have something like this:

assignmentCollection
          // .where('recipients', 'array-contains', user!.id)
          .where('status', 'not-in', recipientAssignmentSkippableStatuses)
          .orderBy('status', 'desc')
          .orderBy('assignedAt', 'desc')
          .orderBy('createdAt', 'asc')

I tried to use something called "array-contains" but:
a) it didn’t work
b) it cause error that cannot be used together with "not-in"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EDIT: I found out that array-contains doesn’t work as I need to pass the whole object for that, thing is that at this moment I know only the ID of the user so I need to find some workaround

>Solution :

I found out that array-contains doesn’t work as I need to pass the whole object for that, the thing is that at this moment I know only the ID of the user so I need to find some workaround.

Yes, in order to return documents that contain a particular object in the array, you need to pass the entire object as an argument, not only a single field.

If you need to filter based on the user ID, then you should consider creating an additional array that only contains user IDs. Then you’ll be able to call:

.where('userIds', 'array-contains', user!.id)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading