![](/img/trans.png)
[英]How to delete a collection with all its sub-collections and documents from Cloud Firestore
[英]How to access sub-collections across multiple documents within a single collection in firestore?
我有一個如下的數據庫結構(為了這個問題而簡化):
Collection: registrations
-> Document: params = {someParameter: "value"}
-> Document: user_01
-> Sub-collection: orders
-> Document: order_AA = {type: "Q1", address: {pincode: "000000", city:"Paris"}
-> Document: order_AB = {type: "Q2", address: {pincode: "111111", city:"London"}
...
-> Document: user_02
-> Sub-collection: orders
-> Document: order_AC = {type: "Q1", address: {pincode: "222222", city:"Berlin"}
-> Document: order_AD = {type: "Q1", address: {pincode: "333333", city:"Paris"}
...
我想要做什么:獲取集合“注冊”中所有用戶的所有訂單列表。 (請注意,“用戶”文檔的數量隨時間變化,子集合中的“訂單”文檔的數量也是如此)
換句話說...查詢 FireStore 以查找集合“registrations”中的所有可用文檔(用戶),並為每個文檔(用戶)在名為“orders”的子集合中找到所有訂單。
我怎樣才能以最短的步驟(最少的查詢)做到這一點?
另外,我是否必須在每個“用戶”文檔中添加一個“虛擬”字段? 我在 StackOverflow 上讀到 FireStore 無法查詢子集合,除非父文檔具有“常規”字段。 即使添加了一個虛擬字段,我也無法讓它工作。
我最近的努力是:
let ordersList = [];
await firestore()
.collection("registrations")
.get()
.then((collectionRef) => {
collectionRef.forEach((userDoc) => {
console.log("==", userDoc.id);
if(userDoc.id.startsWith("user")) {
userDoc.collections("orders")
.get()
.then((ordersSnapshot) => {
ordersSnapshot.forEach((orderDoc) => {
ordersList.push(orderDoc.data());
});
});
}
});
})
.catch(error => {
console.log("Error in retrieving data!");
console.log('Error: ', error);
})
我得到錯誤:
錯誤:[TypeError:userDoc.collections 不是 function。 (在 'userDoc.collections("orders")' 中,'userDoc.collections' 未定義)]
您絕對應該使用 那里描述的collectionGroup()
方法。
您可以使用集合組查詢來查詢 collections 和同名子集合中的所有文檔。 因此,對於子集合“訂單”,您可以使用以下命令查詢 collections 中的所有文檔:
firestore().collectionGroup("orders").get()
如果您不想要所有訂單文檔,則需要以與任何其他查詢相同的方式添加過濾器。 您只能使用每個訂單文檔中可用的字段進行過濾(除非您在文檔中有“用戶”字段可供使用,否則您無法按用戶進行過濾)。
我在 StackOverflow 上讀到 FireStore 無法查詢子集合,除非父文檔具有“常規”字段
這不是真的。 不需要有一個父文檔來查詢它的嵌套子集合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.