0

I want to use a Firebase batched write to make sure that either all of my writes or none of them are happening.

However, I want to create a document (doc1) and a document (doc2) and doc2 should be in a subcollection of doc1.

I think that doc1 needs to exist so that it can have any sub collections (if I am wrong, please correct me). Can I still do both writes in one batched write?

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Patrick
  • 552
  • 5
  • 17

2 Answers2

2

The reference says that writes in a batch are not visible locally (i.e not visible to other writes in the batch). In your example, when you write /collection/doc1/subcollection/doc2, the doc1 does not exist yet...

But, it turns out that you can write to /collection/doc1/subcollection/doc2 event if doc1 does not exist, it will be shown in italics in your console.

So in the end: yes you can do both your writes in a single batch. Doc2 will be within a non existing doc1, but only temporarily during the commit, once the commit is done, all will be OK.

Louis Coulet
  • 3,663
  • 1
  • 21
  • 39
1

Yes, as soon as you know the references of the two documents, you can very well do both writes in one batch, as follows (JavaScript SDK):

    const db = firebase.firestore();

    // Get a new write batch
    let batch = db.batch();

    // Set the value of 'Doc1'
    const doc1Ref = db.collection("col").doc("1");
    batch.set(doc1Ref, { foo: "bar" });

    // Set the value of 'Doc2'
    const doc2Ref = db.collection("col").doc("1").collection("subcol").doc("2");
    batch.set(doc2Ref, { bar: "foo" });

    // Commit the batch
    batch.commit().then(function () {
        // ...
    });

Actually, from a technical perspective, the two documents are totally independent of each other. They 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.

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121