Home > database >  Firebase || read data from database
Firebase || read data from database

Time:12-13

Below is the older version to read data from firestore

db.collection('cafes').get().then(snapshot => {
          snapshot.docs.forEach(doc => {
          console.log(docs)
         });
     });

I think that's why I am getting db.collection() is not a function.


But from the present docs, it is like

async function getcafes(db) {
    const cafesCol = collection(db, 'cafes');
    const cafeSnapshot = await getDocs(cafesCol);
    const cafeList = cafeSnapshot.docs.map(doc => doc.data());
    console.log(cafeList)
    return cafeList;
}

So while using console.log(), it is not giving any output.


<head>
    <script type="module">
      import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.1/firebase-app.js";
      import {
        getFirestore,
        collection,
        getDocs,
      } from "https://www.gstatic.com/firebasejs/9.6.1/firebase-firestore.js";
     

      const firebaseConfig = {
      };

      // Initialize Firebase
      const app = initializeApp(firebaseConfig);
      const db = getFirestore(app);
      const analytics = getAnalytics(app);
      window.db = db; // to make db global variable

      async function getcafes(db) {
        console.log('Fetching Cafes');        
        const cafesCol = collection(db, "cafes");
        const cafeSnapshot = await getDocs(cafesCol);
        const cafeList = cafeSnapshot.docs.map((doc) => doc.data());
        console.log(cafeList);
        return cafeList;
      }

      getcafes() // calling the function

    </script>

CodePudding user response:

The issue is that within getcafes(), db is undefined, as db within the function is a local parameter. Try removing the db parameter from getcafes and allowing it to use the global window.db.

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const analytics = getAnalytics(app);
window.db = db; // to make db global variable
// remove db parameter VV
async function getcafes() {
  console.log("Fetching Cafes");
  // now db here is the global database instead of undefined
  const cafesCol = collection(db, "cafes");
  const cafeSnapshot = await getDocs(cafesCol);
  const cafeList = cafeSnapshot.docs.map((doc) => doc.data());
  console.log(cafeList);
  return cafeList;
}

getcafes(); // calling the function
  • Related