Reputation: 987
I am trying to create a sub-collection in a document and set data to documents in the created sub-collection.
I have tried this but the program crashes every time I run this.
await Firestore.instance
.collection('/path')
.document("documentPath")
.collection('/subCollectionPath')
.document()
.setData({
'TestData': "Data",
}).then((onValue) {
print('Created it in sub collection');
}).catchError((e) {
print('======Error======== ' + e);
});
I have also looked online but I cannot find any documentation for it.
Any ideas?
When I try the above code, the app crashes with the following message
flutter: EVENT StorageTaskEventType.success
*** First throw call stack:
(
0 CoreFoundation 0x0000000111eb61bb __exceptionPreprocess + 331
1 libobjc.A.dylib 0x0000000111454735 objc_exception_throw + 48
2 Runner 0x000000010ce707b1 -[FIRFirestore documentWithPath:] + 257
3 Runner 0x000000010d10662c getDocumentReference + 124
4 Runner 0x000000010d109879 -[FLTCloudFirestorePlugin handleMethodCall:result:] + 2665
5 Flutter 0x000000010e5b99a2 __45-[FlutterMethodChannel setMethodCallHandler:]_block_invoke + 115
6 Flutter 0x000000010e5d6616 _ZNK5shell21PlatformMessageRouter21HandlePlatformMessageEN3fml6RefPtrIN5blink15PlatformMessageEEE + 166
7<…>
Lost connection to device.
Upvotes: 6
Views: 19775
Reputation: 710
Here's the solution, if you want to create a subcollection within a Firestore Transaction:
Firestore.instance.runTransaction((Transaction tx) {
tx.set(Firestore.instance.collection('path').document('documentPath')
.collection('subCollectionPath').document(), {'TestData', 'Data'});
})
NOTE: You cannot create an empty subcollection, you must create the subcollection with at least one document. If you try to create the subcollection with the data field empty, Firestore will create an empty document.
Upvotes: 2
Reputation: 987
Figured out the problem. I was using the wrong syntax. The correct syntax is
Firestore.instance.collection('path').document("documentPath").collection('subCollectionPath').setData({});
The key difference here is that the forward slashes have been removed from the paths name.
Upvotes: 7
Reputation: 3174
For Fetching SubCollection Data, use this query
var query = await databaseReference.collection('Staffs').document("[email protected]"). collection('Wallet').getDocuments()
Upvotes: 1
Reputation: 355
final databaseReference = Firestore.instance;
databaseReference.collection('main collection name').document( unique id).collection('string name').document().setData(); // your answer missing **.document()** before setData
this is the right Syntex
Upvotes: 16