【问题标题】:Firebase || read data from database火力基地 ||从数据库中读取数据
【发布时间】:2021-12-12 11:09:22
【问题描述】:

下面是从firestore读取数据的旧版本

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

我认为这就是为什么我得到 db.collection() 不是一个函数。


但从目前的文档来看,它就像

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

所以在使用 console.log() 时,它没有给出任何输出。


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

【问题讨论】:

  • 代码看起来正确。你能在这个函数的开头添加console.log('Fetching cafes')并检查函数是否被调用吗?
  • 是的,它正在打印 Fetching 数据,但我需要调用 getcafes(),它会触发此错误 --- Uncaught (in promise) FirebaseError: Expected first argument to collection() to be a CollectionReference、DocumentReference 或 FirebaseFirestore
  • 你能分享调用这个函数的代码吗? db 似乎不是 Firestore 实例。
  • 应该是getcafes(db)。由于该函数采用参数数据库,因此它将读取它的值而不是全局值

标签: javascript firebase google-cloud-firestore


【解决方案1】:

问题是在getcafes() 内,dbundefined,因为函数内的db 是一个本地参数。尝试从getcafes 中删除db 参数并允许它使用全局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

【讨论】:

  • 如果我想在另一个脚本中使用getcafes()...我应该做window.getcafes = getcafes...还是有另一种通用方法
  • 是的,你可以这样做
猜你喜欢
  • 1970-01-01
  • 2021-02-03
  • 1970-01-01
  • 2016-09-17
  • 1970-01-01
  • 2020-07-13
  • 2021-06-05
  • 2017-03-26
  • 1970-01-01
相关资源
最近更新 更多