Search code examples
javascriptfirebasegoogle-cloud-firestorefetch

Firebase new namespace for .where() .limit() .orderBy()


to limit the fetch to FirestoreDB I tried to use the recent namespace to getDocs().

const firebaseColRef = collection(db, "collection")

This is what I tried:

const firebaseColRef = collection(db, "collection").limit(x)

And this:

const getDB = async () => {
    const data = await getDocs(firebaseColRef).limit(x);
    setFilmDB(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
  }

In both cases the console prompts:

Uncaught (in promise) TypeError: firebase_firestore__WEBPACK_IMPORTED_MODULE_1__.collection(...).limit is not a function

I went through several documentations, tutorials and articels and was not able to find any other namespace then the above mentioned. And tried any possible append of .limit(x) to get any other result than the console prompt. Nothing worked.

What am I missing ?

Can anyone point me in the right direction ?

Would be very appreciated. Thanks, Anthony


Solution

  • Almost every Firebase method is a top-level function in Modular SDK and can be imported directly from the relevant SDKs. Try refactoring the code as shown below.

    import { collection, getDocs, query, where, limit, orderBy } from "firebase/firestore";
    
    const getDB = async () => {
      const colRef = collection(db, "collection");
    
      // Keep adding query clauses in query()
      // like chaining them in name-spaced V8 version
      const q = query(colRef, where("field", "==", "value"), limit(1));
    
      const data = await getDocs(q);
      console.log(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })))
    }
    

    The name-spaced version of the same query for reference:

    const q = db.collection("col").where("field", "==", "value").limit(1);
    

    You can find list of all functions in the new Firestore SDK in the documentation.

    Also checkout: