【问题标题】:How to solve FirebaseError: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore problem?如何解决 FirebaseError:collection() 的预期第一个参数是 CollectionReference、DocumentReference 或 FirebaseFirestore 问题?
【发布时间】:2021-11-01 23:18:38
【问题描述】:

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

FirebaseError:collection() 的第一个参数应为 CollectionReference、DocumentReference 或 FirebaseFirestore

这是我的自定义钩子之一

import { onAuthStateChanged, User } from '@firebase/auth'
import { doc, onSnapshot, Unsubscribe } from 'firebase/firestore'
import { useEffect, useState } from 'react'
import { auth, fireStore } from './firebase'

export const useUserData = () => {
  const [username, setUsername] = useState<string | null>(null)

  const [currentUser, setCurrentUser] = useState<User | null>(null)

  useEffect(() => {
    let unsubscribe: void | Unsubscribe

    onAuthStateChanged(auth, (user) => {
      if (user) {
        setCurrentUser(user)
        // The Problem is inside this try blog
        try {
          // the onsnapshot function is causing the problem
          console.log('firestore: ', fireStore)
          unsubscribe = onSnapshot(doc(fireStore, 'users', user.uid), (doc) => {
            setUsername(doc.data()?.username)
          })
        } catch (e) {
          console.log(e.message)
        }
      } else {
        setCurrentUser(null)
        setUsername(null)
      }
    })

    return unsubscribe
  }, [currentUser])

  return { currentUser, username }
}

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

import { FirebaseApp, getApps, initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'
import { getFirestore } from 'firebase/firestore/lite'
import { getStorage } from 'firebase/storage'

const firebaseConfig = {
  apiKey: 'some-api',
  authDomain: 'some-auth-domain',
  projectId: 'some-project-id',
  storageBucket: 'some-storage-bucket',
  messagingSenderId: 'some-id',
  appId: 'some-app-id',
  measurementId: 'some-measurement-id',
}

let firebaseApp: FirebaseApp

if (!getApps.length) {
  firebaseApp = initializeApp(firebaseConfig)
}

const fireStore = getFirestore(firebaseApp)
const auth = getAuth(firebaseApp)
const storage = getStorage(firebaseApp)

export { fireStore, auth, storage }

不知道是不是项目初始化的问题。我很确定错误是从我的自定义挂钩文件生成的。我还发现onSnapshot函数一定有问题。我传递 docRef 是错误的还是什么?我在这里做错了什么?

console.log(firestore) 日志:


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

【问题讨论】:

  • 嗯...你能试试doc(fireStore, collection('users'), user.uid)collection 也是从'firebase/firestore' 导入的吗?
  • 糟糕,抱歉,这实际上给出了类型错误
  • 可以分享一下日志截图吗? console.log('firestore: ', fireStore) 这是什么日志?即使是 doc() 方法 atm,错误也会显示 Expected first argument to collection()
  • @Dharmaraj 我编辑了这个问题。看看

标签: javascript firebase google-cloud-firestore firebase-authentication next.js


【解决方案1】:

使用来自lite 库的getFirestore 将不适用于onSnapshot。您正在从lite 版本导入getFirestore

import { getFirestore } from 'firebase/firestore/lite'

将导入更改为:

import { getFirestore } from 'firebase/firestore'

来自documentation

onSnapshot 方法和 DocumentChangeSnapshotListenerOptionsSnapshotMetadataSnapshotOptionsUnsubscribe 对象不包含在 lite 版本中。


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

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

const colRef = collection(db, "collection_name");

【讨论】:

  • 精简版仅在您不需要实时监听器且基本 CRUD 操作足够时才有用。
  • 仍然无法在我的代码中工作。 : (
  • :) 更正了错误。我结合了firebase“Web Version 9”和“Web Version 8”的代码
  • 像魅力一样工作:)
【解决方案2】:

添加到@Dharmaraj,如果您使用的是 firebase react 钩子,请使用相反的方法。

而不是

import { getFirestore } from 'firebase/firestore'

使用

import { getFirestore } from 'firebase/firestore/lite'

【讨论】:

    猜你喜欢
    • 2021-11-02
    • 2021-11-01
    • 2021-11-16
    • 2022-07-02
    • 1970-01-01
    • 2021-11-08
    • 2023-03-15
    • 2021-12-21
    • 1970-01-01
    相关资源
    最近更新 更多