Home > Software engineering >  how do i search trhough array of objects in firestore to fin the smallest value
how do i search trhough array of objects in firestore to fin the smallest value

Time:01-29

I have a collection of documents which looks like so:

  name: string;
  address: IAddress;
  tests: Item[];
  rating?: number;
  photo?: string;

every document has a name as ID and inside every document there is an array of Item and Item is an object of shape:

export type Item = {
  title: string;
  price: number;
};

Now I have a separate collection i which there is a field of min and max price for the Item, and I need to search the abovementioned collection and the array of object inside to find what min and max price of item. How should I do that? I was trying like so

    const q = query(
      collection(firestore, "stores"),
      where("item.title", "==", this.title),
      orderBy("item.price")
    );

And I just realized that this is not just item.title, but this is an array, so it would be item[x].title. How can I search for it in the array? Thanks

CodePudding user response:

There is no way to search across a collection of documents for the one with the lowest price in an array.

You'll want to add a field to the document that captures the lowest price from the array (say item.lowestprice) and then use that in the query:

const q = query(
  collection(firestore, "stores"),
  where("item.title", "==", this.title),
  orderBy("item.lowestprice"), //            
  •  Tags:  
  • Related