![](/img/trans.png)
[英]How delete documents from a Firestore collection with a 'where' clause in Web v9
[英]How to get all documents in Firestore (v9) sub collection
我正在嘗試使用 Firebase V9 獲取所有子集合中的所有文檔,因此我使用了 collectionGroup 來檢索數據。
這是我的 Firestore 架構:
bots (collection)
| id (doc ID)
| order_history (sub collection)
| id (doc ID)
createdBy: uid (user uid)
這就是我嘗試獲取文件的方式:
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 []
}, []);
此代碼返回一個空數組。
我做錯什么了嗎?
我認為您的getOrders
函數是異步函數。 如果您想要調試log
,我認為您應該等待 getOrders completed
,然后orders
已更新。
前任:
useEffect(() => {
console.log('orders ', orders);
}, [orders]);
如果有超過 1 個語句,您的 getOrders 匿名方法執行需要顯式的 return 語句。 當僅存在一條語句時,隱式返回起作用(並且經過一些測試, return await X
似乎也不起作用)。
const getOrders = async () => {
const orders = await getDocs(...);
setOrders(orders.docs.map(...))
}
需要是
const getOrders = async () => {
const orders = await getDocs(...);
return setOrders(orders.docs.map(...))
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.