You can use a batched write, as follows:
// Get a new write batch
let batch = db.batch();
// Set the value of parent
const parentDocRef = db.collection("parentColl").doc();
batch.set(parentDocRef, {
status: 1,
created_at: new Date(),
updated_at: new Date(),
});
//Set the value of a sub-collection doc
const parentDocId = parentDocRef.id;
const subCollectionDocRef = db.collection("parentColl").doc(parentDocId).collection("subColl").doc();
batch.set(subCollectionDocRef, {
...
});
// Commit the batch
await batch.commit();
One key point to note: Actually, from a technical perspective, a parent collection and the sub-collections of the documents in this parent collection are not at all relating to each other.
Let's take an example: Imagine a doc1
document under the col1
collection
col1/doc1/
and another one subDoc1
under the subCol1
(sub-)collection
col1/doc1/subCol1/subDoc1
These two documents (and the two immediate parent collections, i.e. col1
and subCol1
) just share a part of their path but nothing else.
One side effect of this is that if you delete a document, its sub-collection(s) still exist.