Morad Abed
Morad Abed

Reputation: 35

Query array of object in firestore

i have a collection that is called employees, which includes documents and each document contains some data, and an array of objects that is called orgsanizations, for instance:

orgsanizations: [
{
orgId: 'org1',
registrationDate: '08/05/2021',
status: 'pending'
},
{
orgId: 'org2,
registrationDate: '12/01/2021',
status: 'approved'
}
];

I am trying to retrieve all the documents in employees that contains orgId === org1 in the orgsanizations, here is what i tried to do but keeps returning empty array.

  const allEmployees = async () => {
    const employeesList = db.collection('employees');
    const snapshot = await employeesList
      .where('orgsanizations', 'array-contains', { orgId: 'org1' })
      .get();
    if (snapshot.empty) {
      console.log(snapshot.empty);
    } else {
      snapshot.forEach((doc) => {
        console.log(doc.data());
      });
    }
  };
};

Is there a solution for this or should start considering changing the structure to something else? Thanks in advance

Upvotes: 1

Views: 151

Answers (1)

Jason Berryman
Jason Berryman

Reputation: 4908

You can't check for the contents of a map, using array-contains. There are a couple of solutions for this...

  1. Create a second array called orgIds, which contains only the orgId strings. You can then find any documents which contain these orgIds. To achieve this, you will need to write the orgId into the map AND the orgIds array.
  2. Create an organizations sub-collection of your employee document and use a collectionGroup query.
{
  organizations: [
    {orgId: 'org1', registrationDate: '08/05/2021', status: 'pending'},
    {orgId: 'org2', registrationDate: '12/01/2021', status: 'approved'}
  ],
  orgIds: ['org1', 'org2']
}
const employeesList = db.collection('employees');
const snapshot = await employeesList
.where('orgIds', 'array-contains', 'org1')
.get();

You may also want to change your registrationDate to either a Timestamp or an ISO8601 string, so that you can sort them (if needed).

Upvotes: 2

Related Questions