Firestore - batch.add is not a function

artooras picture artooras · Oct 13, 2017 · Viewed 15k times · Source

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.

Answer

Sam Stern picture Sam Stern · Oct 14, 2017

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.