skip to Main Content

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]]
}

2

Answers


  1. 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] ?? {}];
    };
    Login or Signup to reply.
  2. 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).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search