1

I want to know how can I create a collection in flutter that has a subcollection inside it. I know that to create a collection I use this code

firestore.collection('Collection').add({
    'EmployeeID': '123',
    'EmployerID': '234',
    'ProposalID': '456,
  }

but want to achieve something like this

firestore.collection('Collection').add({
    'EmployeeID': '123',
    'EmployerID': '234',
    'ProposalID': '456,
    'Chats':**THIS IS A SUB COLLECTION**
  }

can anyone please help me?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Junaid Tariq
  • 568
  • 8
  • 22

2 Answers2

2

Each add operation can only write a single document at a time. If you need to write multiple documents, you'll need to use a batch write operation.

If you want to write the "parent" document, and the chats subcollection in a single batch write, you can do so by for example generating a UUID for the parent document, and then creating the chat documents under that same path.

var db= Firestore.instance();
var uuid = uuid.v1(); // see https://stackoverflow.com/a/15549397
firestore.collection('Collection').add(
var collectionRef = db.collection("Collection");
var batch = db.batch();
batch.setData(
  db.collection(’Collection’).document(uuid), {
    'EmployeeID': '123',
    'EmployerID': '234',
    'ProposalID': '456',
  })
);
batch.setData(
  db.collection(’Collection’).document(uuid).collection('Chats').document(uuid.v1()), {
    'Message': 'Hello world',
    'Timestamp': FieldValue.serverTimestamp()
  })
)
batch.commit();
vogdb
  • 4,669
  • 3
  • 27
  • 29
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

You would first need to get a specific document, to where you chain another collection method onto the end, which would create a document inside that collection:

firestore.collection('Collection').doc("myDocId").collection("Collection2").add({
    'EmployeeID': '123',
    'EmployerID': '234',
    'ProposalID': '456,
    'Chats':**THIS IS A SUB COLLECTION**
  }
``
danwillm
  • 469
  • 3
  • 17