Home > Net >  Firestore: Get multiple documents via complex fieldPath (where function)
Firestore: Get multiple documents via complex fieldPath (where function)

Time:10-02

I safed different products in my Firestore and they are available for purchase on different days of the week. So I safed the availability on different days as an Array of 7 boolean values in my Firestore.

weekdays = [true, true, true, false, false, true, false];

Now if I wanna get all products that are available on Friday I would have to do something like this:

// assume date.getDay() is 5

const q = query(
  collection(db, "bakerys", `${bakery.id}`, "products"), 
  where(`weekdays[${date.getDay()}]`, "==", "true")
);
const querySnapshot = await getDocs(q);

This doesn't seem to work. Do I really have to store every weekday in its own value separately in order to make this work or is there a way to get this work differently.

CodePudding user response:

You can just store the days directly instead of a boolean value like this:

weekdays = ['Monday', 'Friday'];

Then execute this query:

const q = query(
  collection(db, "bakerys", `${bakery.id}`, "products"), 
  where(`weekdays`, "array-contains", "Monday")
);

This query will fetch all documents where the weekdays array contains Monday. If you want to store boolean values with day index then you would have to store a map like this:

weekdays = {
  1: true,
  5: false
}

Here you can use the following query:

const q = query(
  collection(db, "bakerys", `${bakery.id}`, "products"), 
  where(`weekdays.${date.getDay()}`, "==", true)
);

Additionally do note that your original array contains boolean values but your query had "true" (string). Make sure the types in db and query match.

  • Related