Home > Back-end >  Resolving multiple promises for fetching data from firestore
Resolving multiple promises for fetching data from firestore

Time:12-14

I have the following code, I want to fetch data from two collections of firestore,the first element of each collection data. What reason data is not being returned ?

const myFunction = async () => {
  const usersData = await db.collection("users").get()
  const productsData = await db.collection("products").get()
  return [usersData[0], productsData[0]]
}

CodePudding user response:

Try this solution

 const myFunction = async () => {
    const users =
      (await db.collection("users").get()).docs.map((each) => each.data()) || [];
    const products =
      (await db.collection("products").get()).docs.map((each) => each.data()) ||
      [];
    // making sure the solution doesn't return undefined or null
    return [users?.[0] ?? {}, products?.[0] ?? {}];
};

CodePudding user response:

You are using get() on a CollectionReference that'll fetch all the N documents present in that collection and you'll be charged for N reads. Instead, you should be using a query with limit 1 that'll only fetch the first document ordered by the constraints that you specify as shown below:

const myFunction = async () => {
  const [usersData, productsData] = await Promise.all([
    db.collection("users").limit(1).get(),
    db.collection("products").limit(1).get()
  ])

  return [usersData.docs[0]?.data(), productsData.docs[0]?.data()]
}

The queries above will only cost 2 reads (1 from each collection).

  • Related