Firestore array-contains查询问题:组件传参获取数据返回空数组
解决方案
1. 修复异步函数语法错误
你的函数里使用了await但未声明为async,这会触发语法错误,导致查询无法正常执行。必须给函数加上async关键字:
const fetchCategoryProducts = async (catId)=>{ const categoryProductsCollection = query(collection(db, "Product"), where("categories", "array-contains", catId)) const getCategoryProducts = await getDocs(categoryProductsCollection); const categoryProducts = getCategoryProducts.docs.map(item=>{ const data = item.data(); data.id = item.id; return data }) console.log(categoryProducts) }
2. 排查catId的匹配问题
固定字符串能查到数据,但props传入的catId不行,核心原因是传入的catId和Firestore数组中的字符串不完全一致,可以从以下几点检查:
- 检查catId是否带有前后空格:比如Firestore中存储的是
"اقلام",但传入的是"اقلام "(末尾多了空格) - 对比字符编码:阿拉伯语里存在部分形似但编码不同的字符,直接打印
catId和从Firestore取出的字符串,或用JSON.stringify查看原始字符的差异 - 确认参数传递正常:调用函数前先打印
catId,确保它不是undefined或null
3. 分步调试查询逻辑
先把查询条件换回能正常工作的固定字符串,确认查询逻辑本身没有问题,再替换为catId:
// 先测试固定值,验证查询逻辑正常 const categoryProductsCollection = query(collection(db, "Product"), where("categories", "array-contains", "اقلام"))
如果固定值能查到数据,再重点对比固定值和传入catId的差异,即可定位问题。
内容的提问来源于stack exchange,提问作者Mohammed Refat
相关产品推荐
相关产品推荐

