Héctor
Héctor

Reputation: 26054

How can I make this Firestore query?

I'm a Firestore newbie and I need to make a query. I have this database structure:

{
  "businesses": {
    "1" : {
      "name": "bla",
      "employees": {
        "1" : {
          "name": "Juan",
          "schedules": {
            "1": {
              "scheduleId" : "72",
              "from": "21/08/2020"
            }
          }
        },
        "schedules": {
          "72": {
            //some properties
          }
        }
      }
    }
  }
}

Given a businessId and a scheduleId, I need to fetch all the business' employees having that scheduleId assigned.

I have tried this:

export async function getEmployeesWithSchedule(businessId: string, scheduleId: string): Promise<Employee[]> {
    const docs = (await admin.firestore().collection(`businesses/${businessId}/employees`)
         .where("schedules.scheduleId", "==", scheduleId)
         .get()).docs;
   //extract results
}

But I'm geting no results. How should I make this query?

Upvotes: 1

Views: 92

Answers (1)

hnnngwdlch
hnnngwdlch

Reputation: 3041

Try the following where clause. You should only get back docs where the schedules map contains a key-value-pair with key scheduleId and a non-null value:

const docs = (await admin.firestore().collection(`businesses/${businessId}/employees`)
         .where(`schedules.${scheduleId}`, "!=", null)
         .get()).docs;

Upvotes: 1

Related Questions