【问题标题】:db.collection is not a function firebase firestoredb.collection 不是函数 firebase firestore
【发布时间】:2021-10-17 22:04:53
【问题描述】:

您好,我正在尝试使用 firebase 配置 react 应用程序并使用 firestore。

"firebase": "^9.1.3"

我按照官方文档中的说明进行操作。

这是我的 congig.js 文件。

import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';

const firebaseConfig = {
    apiKey: '****',    
    authDomain: '*****',    
    projectId: '*****',    
    storageBucket: '*****',    
    messagingSenderId: '****',    
    appId: '*****',
};

const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);

我确定这已被初始化。

当我导出它并在其他文件中使用它时。 collection 在 vs 代码中显示为灰色,这意味着我没有使用导入。

数据库服务.js

import { db } from './config';
import { collection, doc } from 'firebase/firestore';

export const getChapters = (scanId) => {
    db.collection('somecollection')
        .doc(scanId)
        .get()
        .then((doc) => {
            if (doc.exists) {
                console.log('Document data:', doc.data());
            } else {
                // doc.data() will be undefined in this case
                console.log('No such document!');
            }
        })
        .catch((error) => {
            console.log('Error getting document:', error);
        });
};

错误:类型错误:config__WEBPACK_IMPORTED_MODULE_0_.db.collection 不是函数

我尝试过兼容和精简版。遇到同样的问题。

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    这是 v8/compat 语法:

    db.collection('somecollection')
        .doc(scanId)
        .get()
        .then((doc) => {
    

    在 v9/modular 语法中,等价于:

    getDoc(doc(db, 'somecollection', scanId))
        .then((doc) => {
    

    为了转换这种类型的东西,我发现将 Firebase documentationupgrade guide 放在手边是最容易的。

    【讨论】:

      【解决方案2】:

      Firebase 在版本 9 中已将其 API 更改为新的模块化语法。您使用的是版本 8 中的旧语法。您可以在此处阅读有关此内容的更多信息并找到有关升级代码的说明:https://firebase.google.com/docs/web/modular-upgrade

      此外,在 Firebase 文档的任何地方,它们现在都有 2 个单独的示例:一个用于旧语法,一个或新的模块化语法:https://firebase.google.com/docs/firestore/query-data/get-data

      【讨论】:

      • 我想使用它的模块化版本并尝试了它有相同错误的两个版本
      猜你喜欢
      • 2021-11-17
      • 2021-11-05
      • 2021-10-31
      • 2021-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      相关资源
      最近更新 更多