skip to Main Content

i am trying to pull a collection from firestore using firebase functions gen2. my code looks like below

const { initializeApp } = require('firebase-admin/app');
const { getFirestore } = require('firebase-admin/firestore');
const { getDocs} = require("firebase-functions/v2/firestore");

initializeApp();
const db = getFirestore();

const cors = require('cors')({origin:true});

export const getReviews = onRequest(async(request, response) => {
    cors(request, response, async() => {
        logger.info("getReviews logging!", {structuredData: true});
   
        const reviews:any = []
        const appRef = db.collection("feedback");
        const appQuery = db.query(appRef);
        const querySnapshot = await getDocs(appQuery);
        querySnapshot.forEach((doc:any) => {
            let data:any 
            data = doc.data()
            reviews.push(data)
        });

        response.send(reviews);
      });
  
 });

on running this fails with error query is not a function.

2

Answers


  1. To query a collection in firebase function v2 you should use
    await db.collection("feedback").where("user", "==", "bob").get()

    Login or Signup to reply.
  2. At the time of writing, the Node SDKs for Firebase still use the namespaced API syntax. For the firebase-admin SDK, this is provided by the @google-cloud/firestore Client SDK. query() was introduced with the Firebase Cloud Firestore Modular SDK and is not available in the Node SDKs.

    To correct your code, you would replace these lines:

    const appRef = db.collection("feedback");
    const appQuery = db.query(appRef);
    const querySnapshot = await getDocs(appQuery);
    

    with

    const appColRef = db.collection("feedback"); // best practice to use "ColRef" instead of just "Ref"
    const querySnapshot = await appColRef.get()
    

    To a certain extent, you can refer to the Modular SDK Upgrade Guide and use it to downgrade your familiarity with the client side code.

    Note: firebase-functions/v2/firestore is used to define 2nd Gen Firestore Cloud Functions and is not used to access your Firestore database. That is the responsibility of firebase-admin/firestore.

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