I am using the Firestore Database. And I want to add collections and data via dart code.
This is basically how my map looks:
Map map = {
'key1': <Map>[],
'key2': <Map>[],
'key3': <Map>[],
}
I basically want my firebase database structure to look like:
collectionName -> key1 -> Map1 -> "nestedMapKey1":"value"
"nestedMapKey2":"value"
Map2 -> "nestedMapKey1":"value"
Map3 -> etc.
key2 -> Map1
Map2
Map3
key3 -> Map1
Map2
I tried things like that but that’s obviously not the result I want like above.
void uploadCourses(){
for (var k in coursesMap.keys){
for (var v in coursesMap[k]){
FirebaseFirestore.instance.collection('courses').doc('$k').collection('$k').add(v);
}
}
}
I guess what I want is this:
FirebaseFirestore.instance.collection('courses').collection('$k').add(v);
Which is not supported. Are there any other ways to do it? Or can I simply not fill a collection with a collection?
2
Answers
Firestore’s data model starts with a number of collections at the top. Then each collection has a number of documents, which in turn can each have a number of subcollections, which each can have a number of documents, etc.
There is no way to nest subcollections directly under a collection. You will always need a document in between.
If I don’t have a need for multiple documents, I typically create one with an easy name, such as
default
and nest my subcollections under that.Just consider each key as a document and each map as attributes of your doc. Latter it is possible to add or edit the maps individually using update.