Firestore - batch.add is not a function

The documentation for Firestore batch writes lists only set(), update() and delete() as permitted operations.

Is there no way to add an add() operation to the batch? I need a document to be created with an auto-generated id.


Solution 1:

You can do this in two steps:

// Create a ref with auto-generated ID
var newCityRef = db.collection('cities').doc();

// ...

// Add it in the batch
batch.set(newCityRef, { name: 'New York City' });

The .doc() method does not write anything to the network or disk, it just makes a reference with an auto-generated ID you can use later.

Solution 2:

In my case, using AngularFire2, I had to use the batch.set() method, passing as first parameter the document reference with an ID previously created, and the reference attribute:

import { AngularFirestore } from '@angular/fire/firestore';
...
private afs: AngularFirestore
...
batch.set(
    this.afs.collection('estados').doc(this.afs.createId()).ref,
    er.getData()
  );

Solution 3:

According to the docs

Behind the scenes, .add(...) and .doc().set(...) are completely equivalent, so you can use whichever is more convenient.

Perhaps this applies to batches as well?

Solution 4:

For PHP you can try :

$batch = $db->batch();
$newCityRef = $db->collection('cities')->newDocument();
$batch->set($newCityRef , [ 'name'=>'New York City' ]);