简体   繁体   中英

How to create a collection which has a sub collection in firebase firestore?

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?

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

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**
  }
``

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM