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

如何修复FirebaseError:预期类型为'Query',实际为自定义Firestore对象

Firestore查询错误:Expected type 'Query', but it was: a custom Firestore object 解决思路

错误原因分析

你的代码存在几个关键问题,导致Firestore无法正确识别查询对象:

  • 未导入collection、limit、where等Firestore核心方法,调用时引发类型不匹配
  • getDocs调用方式错误,未等待异步操作完成就直接访问docs属性
  • getStaticPaths中getDocs的参数格式错误,未正确生成集合引用
  • 变量post未完成赋值逻辑

具体修复步骤

  1. 补充必要的Firestore方法导入
    在原有导入语句中添加缺失的方法:

    import { getDocs, query, collection, limit, where } from 'firebase/firestore'
    
  2. 修正getStaticProps中的查询逻辑
    先等待getDocs异步请求完成,再处理返回的快照,同时完善post变量的赋值:

    if (userDoc) {
      const postRefQuery = query(
        collection(firestore, 'posts'),
        limit(1),
        where('slug', "==", slug)
      );
      const snapshot = await getDocs(postRefQuery);
      if (!snapshot.empty) {
        const doc = snapshot.docs[0];
        post = postToJSON(doc);
        path = post.path;
      }
    }
    
  3. 修复getStaticPaths中的集合引用
    getDocs需要接收集合引用作为参数,而非直接传入firestore实例和集合名:

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

完整修复后的代码

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, collection, limit, where } 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 snapshot = await getDocs(postRefQuery);
    if (!snapshot.empty) {
      const doc = snapshot.docs[0];
      post = postToJSON(doc);
      path = post.path;
    }
  }

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

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

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

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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 19:42:59