如何修复“FirebaseError:应为类型“Query”,但实际为:一个自定义的Firestore对象”

64jmpszr  于 2023-03-19  发布在  其他
关注(0)|答案(1)|浏览(94)

我正在使用一个查询搜索我的文章集合来检索一个文档,其中slug字段等于在URL中找到的一个。(例如,“http://localhost:3000/jeff 235/random-post-2”将找到slug字段值为“random-post-2”的文档。)然而,我得到一个错误:
Firebase错误:应为类型“Query”,但实际为:自定义Firestore对象
我试过查看其他问题,但似乎没有一个能帮到我?下面是我检索文档的页面的代码,其中有错误:

import styles from '../../styles/Post.module.css';
import PostContent from '../../components/PostContent';
import { firestore, getUserWithUsername, postToJSON } from '../../lib/firebase';
import { useDocumentData } from 'react-firebase-hooks/firestore';
import { getDocs, query } from 'firebase/firestore'

export async function getStaticProps({ params }) {
  const { username, slug } = params;
  const userDoc = await getUserWithUsername(username);

  let post;
  let path;

  if (userDoc) {
    const postRefQuery = query(
      collection(firestore, 'posts'),
      limit(1),
      where('slug', "==", slug)
    );
    const postRef = postToJSON(await getDocs(postRefQuery).docs[0]);
    path = postRef.path;
  }

  return {
    props: { post, path },
    revalidate: 5000,
  };
}

export async function getStaticPaths() {
  const snapshot = await getDocs(firestore, 'posts');

  const paths = snapshot.docs.map((doc) => {
    const { slug, username } = doc.data();
    return {
      params : { slug, username },
    };
  });

  return {
    paths,
    fallback: 'blocking',
  };
}

有什么想法吗?

lsmepo6l

lsmepo6l1#

问题很可能来自这里:

const snapshot = await getDocs(firestore, 'posts');

getDoc函数接受QueryCollectionReference,但您传递给它的是firestore对象。
这更可能是您想要的:

const snapshot = await getDocs(collection(firestore, 'posts'));

相关问题