[英]How to get all documents in Firestore (v9) sub collection
I'm trying to get all documents in all sub-collection with Firebase V9, so I used collectionGroup to retrieve the data.我正在尝试使用 Firebase V9 获取所有子集合中的所有文档,因此我使用了 collectionGroup 来检索数据。
Here is my Firestore architecture :这是我的 Firestore 架构:
bots (collection)
| id (doc ID)
| order_history (sub collection)
| id (doc ID)
createdBy: uid (user uid)
And this is how I try to get documents :这就是我尝试获取文件的方式:
const [orders, setOrders] = useState([]);
const { user } = useAuth();
const getOrders = async () => {
const orders = await getDocs(query(collectionGroup(db, 'order_history'), where('createdBy', '==', user.uid)));
setOrders(orders.docs.map((doc) => ({
...doc.data()
})))
}
useEffect(() => {
getOrders();
console.log('orders ', orders); // return []
}, []);
This code returns an empty array.此代码返回一个空数组。
Did I do something wrong?我做错什么了吗?
I think your getOrders
function is asynchronus function.我认为您的
getOrders
函数是异步函数。 If you want debug log
I think you should waiting for getOrders completed
then orders
had been updated.如果您想要调试
log
,我认为您应该等待 getOrders completed
,然后orders
已更新。
Ex:前任:
useEffect(() => {
console.log('orders ', orders);
}, [orders]);
Your getOrders anonymous method execution requires an explicit return statement if there's more than 1 statement.如果有超过 1 个语句,您的 getOrders 匿名方法执行需要显式的 return 语句。 Implicit returns work when only a single statement exists (and after some testing,
return await X
doesn't appear to work either).当仅存在一条语句时,隐式返回起作用(并且经过一些测试,
return await X
似乎也不起作用)。
const getOrders = async () => {
const orders = await getDocs(...);
setOrders(orders.docs.map(...))
}
Needs to be需要是
const getOrders = async () => {
const orders = await getDocs(...);
return setOrders(orders.docs.map(...))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.