如何解决 FirebaseError: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore 问题?

Pra*_*nta 29 javascript firebase firebase-authentication next.js google-cloud-firestore

我正在尝试使用 next.js 设置 Firebase。我在控制台中收到此错误。

\n
\n

FirebaseError:预计 collection() 的第一个参数是 CollectionReference、DocumentReference 或 FirebaseFirestore

\n
\n

这是我的自定义钩子之一

\n
import { onAuthStateChanged, User } from '@firebase/auth'\nimport { doc, onSnapshot, Unsubscribe } from 'firebase/firestore'\nimport { useEffect, useState } from 'react'\nimport { auth, fireStore } from './firebase'\n\nexport const useUserData = () => {\n  const [username, setUsername] = useState<string | null>(null)\n\n  const [currentUser, setCurrentUser] = useState<User | null>(null)\n\n  useEffect(() => {\n    let unsubscribe: void | Unsubscribe\n\n    onAuthStateChanged(auth, (user) => {\n      if (user) {\n        setCurrentUser(user)\n        // The Problem is inside this try blog\n        try {\n          // the onsnapshot function is causing the problem\n          console.log('firestore: ', fireStore)\n          unsubscribe = onSnapshot(doc(fireStore, 'users', user.uid), (doc) => {\n            setUsername(doc.data()?.username)\n          })\n        } catch (e) {\n          console.log(e.message)\n        }\n      } else {\n        setCurrentUser(null)\n        setUsername(null)\n      }\n    })\n\n    return unsubscribe\n  }, [currentUser])\n\n  return { currentUser, username }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

我还有这个 firebase.ts 文件,我在其中初始化了我的 firebase 应用程序

\n
import { FirebaseApp, getApps, initializeApp } from 'firebase/app'\nimport { getAuth } from 'firebase/auth'\nimport { getFirestore } from 'firebase/firestore/lite'\nimport { getStorage } from 'firebase/storage'\n\nconst firebaseConfig = {\n  apiKey: 'some-api',\n  authDomain: 'some-auth-domain',\n  projectId: 'some-project-id',\n  storageBucket: 'some-storage-bucket',\n  messagingSenderId: 'some-id',\n  appId: 'some-app-id',\n  measurementId: 'some-measurement-id',\n}\n\nlet firebaseApp: FirebaseApp\n\nif (!getApps.length) {\n  firebaseApp = initializeApp(firebaseConfig)\n}\n\nconst fireStore = getFirestore(firebaseApp)\nconst auth = getAuth(firebaseApp)\nconst storage = getStorage(firebaseApp)\n\nexport { fireStore, auth, storage }\n
Run Code Online (Sandbox Code Playgroud)\n

不知道问题是否出在项目初始化上。我很确定错误是由我的自定义挂钩文件生成的。我也发现肯定是onSnapshot功能有问题。我传递的 docRef 是错误的还是什么?我在这里做错了什么?

\n

日志console.log(firestore)

\n
\n    type: "firestore-lite"\n    _app: FirebaseAppImpl\n    _automaticDataCollectionEnabled: false\n    _config: {name: "[DEFAULT]", automaticDataCollectionEnabled: false}\n    _container: ComponentContainer {name: "[DEFAULT]", providers: Map(15)}\n    _isDeleted: false\n    _name: "[DEFAULT]"\n    _options:\n    apiKey: 'some-api'\n    authDomain: 'some-auth-domain'\n    projectId: 'some-project-id'\n    storageBucket: 'some-storage-bucket'\n    messagingSenderId: 'some-id'\n    appId: 'some-app-id'\n    measurementId: 'some-measurement-id'\n    [[Prototype]]: Object\n    automaticDataCollectionEnabled: (...)\n    config: (...)\n    container: (...)\n    isDeleted: (...)\n    name: (...)\n    options: (...)\n    [[Prototype]]: Object\n    _credentials: Q {auth: AuthInterop}\n    _databaseId: H {projectId: "next-firebase-fireship", database: "(default)"}\n    _persistenceKey: "(lite)"\n    _settings: ee {host: "firestore.googleapis.com", ssl: true, credentials: undefined, ignoreUndefinedProperties: false, cacheSizeBytes: 41943040, \xe2\x80\xa6}\n    _settingsFrozen: false\n    app: (...)\n    _initialized: (...)\n    _terminated: (...)\n\n
Run Code Online (Sandbox Code Playgroud)\n

Dha*_*raj 64

getFirestore从库中使用lite不适用于onSnapshot. 您正在getFirestorelite以下版本导入:

import { getFirestore } from 'firebase/firestore/lite'
Run Code Online (Sandbox Code Playgroud)

将导入更改为:

import { getFirestore } from 'firebase/firestore'
Run Code Online (Sandbox Code Playgroud)

文档来看,

方法onSnapshotDocumentChangeSnapshotListenerOptionsSnapshotMetadataSnapshotOptionsUnsubscribe对象不包含在lite版本中。


显示此错误的另一个原因可能是将无效的第一个参数传递给collection()doc()函数。它们都将 Firestore 实例作为第一个参数。

// Ensure that "db" is defined and initialized
const db = getFirestore();
// console.log(db);

const colRef = collection(db, "collection_name");
Run Code Online (Sandbox Code Playgroud)

  • 在我的代码中仍然不起作用。:( (6认同)

Fre*_*sar 12

不要混合使用firestore/litewithfirestore

您需要在导入中使用:

'firebase/firestore'
Run Code Online (Sandbox Code Playgroud)

或者

'firebase/firestore/lite'
Run Code Online (Sandbox Code Playgroud)

两者不在同一个项目中。

在您的情况下,该firebase.ts文件正在使用:

'firebase/firestore'
Run Code Online (Sandbox Code Playgroud)

在你的hook

'firebase/firestore/lite'
Run Code Online (Sandbox Code Playgroud)

因此,您正在初始化精简版,但随后使用完整版本。

请记住,两者都有其优点,但我建议根据您的情况选择其中之一并使用它。然后错误就会消失。