【发布时间】: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