如何修复FirebaseError:预期类型为'Query',实际为自定义Firestore对象
Firestore查询错误:Expected type 'Query', but it was: a custom Firestore object 解决思路
错误原因分析
你的代码存在几个关键问题,导致Firestore无法正确识别查询对象:
- 未导入
collection、limit、where等Firestore核心方法,调用时引发类型不匹配 getDocs调用方式错误,未等待异步操作完成就直接访问docs属性getStaticPaths中getDocs的参数格式错误,未正确生成集合引用- 变量
post未完成赋值逻辑
具体修复步骤
补充必要的Firestore方法导入
在原有导入语句中添加缺失的方法:import { getDocs, query, collection, limit, where } from 'firebase/firestore'修正
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; } }修复
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
相关产品推荐
相关产品推荐

