How to access sub-collections across multiple documents within a single collection in firestore?

放肆的年华 提交于 2020-06-17 09:39:12

问题


I have a database structure as follows (simplified for purposes of this question):

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"}
            ...

What I want to do: Obtain a list of all the orders across all users within the collection "registrations". (please note that the number of "user" documents is variable over time, and also the number of "order" documents within the sub-collection)

In more words... Query FireStore to find all the available documents (users) within the collection "registrations", and for each of these documents (users) find all the orders in their sub-collection named "orders".

How can I do this in the shortest steps (fewest queries)?

Also, is it essential for me to add a "dummy" field within each "user" document? I have read on StackOverflow that FireStore cannot query sub-collections unless the parent document has "regular" fields. Even after adding a dummy field, I was unable to get it to work.

My most recent effort has been:

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);
    })

I get the error:

Error: [TypeError: userDoc.collections is not a function. (In 'userDoc.collections("orders")', 'userDoc.collections' is undefined)]


回答1:


You should definitely use the collectionGroup() method as described there.




回答2:


You can use a collection group query to query all documents among collections and subcollections with the same name. So, for the subcollection "orders", you can query all documents in those collections using:

firestore().collectionGroup("orders").get()

If you don't want all of the order documents, you will need to add a filter in the same way that you would any other query. You can only filter using the fields available in each orders document (you can't filter per user unless you have a "user" field in the document to use).

I have read on StackOverflow that FireStore cannot query sub-collections unless the parent document has "regular" fields

This is not true. There is no need to have a parent document in place to query its nested subcollections.



来源:https://stackoverflow.com/questions/62137635/how-to-access-sub-collections-across-multiple-documents-within-a-single-collecti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!