Reputation: 234
I am asking this a lot here, I know, but nobody gives me a right answer.
I just need to return a list with values from a sub collection of Firebase.
This is my code:
List mapToList({DocumentSnapshot doc, List<DocumentSnapshot> docList}) {
if (docList != null) {
List<Store> storeList = [];
docList.forEach((document) async {
String productName;
String name = document.data[StringConstant.nameField];
QuerySnapshot productRef = await document.reference.collection('products').getDocuments();
productRef.documents.forEach((value){
productName = value["name"];
});
Store otherStore = Store(name, productName);
storeList.add(otherStore);
});
print(storeList.length);
return storeList;
} else {
return null;
}
}
Or I want something like this:
List mapToList({DocumentSnapshot doc, List<DocumentSnapshot> docList}) {
if (docList != null) {
List<Store> storeList = [];
docList.forEach((document) async {
//I KNOW THIS IS WRONG, BUT I NEED SOMETHING LIKE THE LINE BELOW
String productName = document.data.reference.collection("products").data["productName];
String name = document.data["name];
Store otherStore = Store(name, productName);
storeList.add(otherStore);
});
return storeList;
} else {
return null;
}
}
How can I get this list?
Upvotes: 0
Views: 64
Reputation: 853
Subcollections do not have "fields" that you can access directly in the manner you wish to. As is explained in The Cloud Firestore Data Model, collections and subcollections both are essentially just names for a set of documents. You cannot access fields directly in a subcollection, you must first reference a document in the subcollection, and then the document's fields. Documents are the only things that contain fields.
For your situation, I'd suggest simply storing a map in the products field of each of the documents you're considering here. Or, if you absolutely must use a subcollection (perhaps as a means of keeping flexibility for future schema changes), use document.collection('products').document('productName')["value"]
or something similar.
Subcollections work like this because they are inteded to provide a method to store data relevant only to a particular document, such that the document's security settings are thus also inherently applied to the subcollection. As in the example in the link - rooms
is a collection of chatrooms, each of which is a document with its name and a reference to a messages
subcollection, each of which contains the message and its author. The messages
subcollection loses context without the room
document.
Upvotes: 1