1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I think your second option is not possible tho as I just realised you get an error as return when trying to use "[" or "]" in the fieldPath. Also, when you try to enter the 1 of weekdays in your example (or other attrbutes), wouldn't you do it like this: weekdays['1'] and not like this: weekdays[1]? Thanks again for the quick response!
@Sumsidum correct my answer a bit. I missed the dot notation there in 2nd snippet

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.