You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase TypeError: db.collection不是函数问题解决请求

问题描述

开发中出现错误:TypeError: _firebase__WEBPACK_IMPORTED_MODULE_3__.db.collection is not a function,该错误触发于Posts.js文件。已尝试更新代码至最新版本,问题仍未解决。

相关代码

firebase.js 代码

import { initializeApp } from 'firebase/app';
import { getStorage, ref, getDownloadURL, uploadString } from 'firebase/storage';
import { getFirestore, collection, addDoc, serverTimestamp } from 'firebase/firestore';

// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "xxxxxxxx",
  authDomain: "xxxxxxxx.firebaseapp.com",
  projectId: "xxxxxxxx",
  storageBucket: "xxxxxxxx.appspot.com",
  messagingSenderId: "xxxxxxxx",
  appId: "xxxxxxxx",
  measurementId: "xxxxxxxx"
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const storage = getStorage(app);

export { app, db, storage, collection, addDoc, serverTimestamp, ref, getDownloadURL, uploadString };

inputBox.js 代码

import { db, collection, storage, addDoc, serverTimestamp, ref, getDownloadURL, uploadString  } from '../firebase'

const sendPost = (e) => {
  e.preventDefault();

  if (!inputRef.current.value) return;

  addDoc(collection(db, 'posts'), {
    message: inputRef.current.value,
    name: session.user.name,
    email: session.user.email,
    image: session.user.image,
    timestamp: serverTimestamp()
  })
    .then((docRef) => {
      if (imageToPost) {
        const uploadTask = uploadString(ref(storage, `posts/${docRef.id}`), imageToPost, 'data_url');

        removeImage();

        uploadTask.on('state_changed',
          null,
          (error) => {
            console.error(error);
          },
          () => {
            getDownloadURL(ref(storage, `posts/${docRef.id}`))
              .then((downloadURL) => {
                return updateDoc(doc(db, 'posts', docRef.id), {
                  postImage: downloadURL
                });
              })
              .catch((error) => {
                console.error(error);
              });
          }
        );
      }
    })
    .catch((error) => {
      console.error(error);
    });

  inputRef.current.value = '';
};

Posts.js 代码

import React from 'react';
import { useCollectionData } from 'react-firebase-hooks/firestore';
import { db } from '../firebase';
import Post from './Post';

const Posts = () => {
  const postsRef = db.collection('posts').orderBy('timestamp', 'desc');
  const [realtimePosts, loading, error] = useCollectionData(postsRef, { idField: 'id' });

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  return (
    <div>
      {realtimePosts.map((post) => (
        <Post
          key={post.id}
          name={post.name}
          message={post.message}
          email={post.email}
          timestamp={post.timestamp}
          image={post.image}
          postImage={post.postImage}
        />
      ))}
    </div>
  );
};

export default Posts;
解决方案

错误根源是你使用的是Firebase v9+模块化API,但Posts.js里仍沿用旧版命名空间模式的db.collection()写法,该写法在v9+模块化API中已废弃。

修改步骤:

  1. 在Posts.js中导入collection、query和orderBy函数:
import { db, collection, query, orderBy } from '../firebase';
  1. 将postsRef的写法替换为模块化API格式:
    原代码:
const postsRef = db.collection('posts').orderBy('timestamp', 'desc');

修改为:

const postsRef = query(collection(db, 'posts'), orderBy('timestamp', 'desc'));

完整修改后的Posts.js代码:

import React from 'react';
import { useCollectionData } from 'react-firebase-hooks/firestore';
import { db, collection, query, orderBy } from '../firebase';
import Post from './Post';

const Posts = () => {
  const postsRef = query(collection(db, 'posts'), orderBy('timestamp', 'desc'));
  const [realtimePosts, loading, error] = useCollectionData(postsRef, { idField: 'id' });

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  return (
    <div>
      {realtimePosts.map((post) => (
        <Post
          key={post.id}
          name={post.name}
          message={post.message}
          email={post.email}
          timestamp={post.timestamp}
          image={post.image}
          postImage={post.postImage}
        />
      ))}
    </div>
  );
};

export default Posts;

注:你的inputBox.js已正确使用模块化的collection(db, 'posts')写法,保持即可。

内容的提问来源于stack exchange,提问作者saddysad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 01:47:18