0

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"

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

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Jacki
  • 632
  • 3
  • 14
  • 26

1 Answers1

2

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)
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • 1
    I was afraid that's the only way, oki so I will poke backend to add extra field then, thanks! – Jacki Feb 10 '23 at 12:42