【问题标题】:× FirebaseError: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore× FirebaseError:collection() 的第一个参数应该是 CollectionReference、DocumentReference 或 FirebaseFirestore
【发布时间】:2021-11-02 07:55:36
【问题描述】:

您好,我有这段代码,我使用的是 firebase v9 web。这是我的代码:

 const [post, setPosts] = useState([]);

  useEffect(() => {
    const q = query(collection(db, "posts"));

    onSnapshot(q, (querySnapshot) => {
      setPosts(
        querySnapshot.docs.map((doc) => ({ id: doc.id, data: doc.data() }))
      );
    });
  });

【问题讨论】:

  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: javascript firebase google-cloud-firestore


【解决方案1】:

documentation 包含 V8 名称空间和 V9 模块化语法的示例:

import { getFirestore, collection, query, where, onSnapshot } from "firebase/firestore";

const db = getFirestore()

const q = query(collection(db, "posts"));

const unsubscribe = onSnapshot(q, (querySnapshot) => {
  setPosts(querySnapshot.docs.map((doc) => ({ id: doc.id, data: doc.data() })))
});

【讨论】:

  • 我这样做了,但现在我遇到了这个错误。 src\Feed.js Line 20:16: 'snapshot' is not defined no-undef
  • @TheDevZak 检查更新的答案......它必须是querySnapshot.map()
  • 我改为 querySnapshot.map() 但现在我有 × FirebaseError: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore
  • @TheDevZak 通过 db ?检查更新的答案。
  • @TheDevZak 你还没有const db = getFirestore() 我的回答。
【解决方案2】:

我曾经创建了 firebaseApp,以后可以在应用程序中使用它。由于 firebase@9 我得到了同样的错误。现在我在似乎可行的数据库调用之前创建了 firebaseApp。

const [post, setPosts] = useState([]);

useEffect(() => {
    const app = initializeApp(firebaseOption);
    const db = getFirestore(app);
    const q = query(collection(db, "posts"));

    onSnapshot(q, (querySnapshot) => {
      setPosts(
        querySnapshot.docs.map((doc) => ({ id: doc.id, data: doc.data() }))
      );
    });
  });

【讨论】:

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