// 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.
Create the reference to the collection in which you are going to add the batch data
We loop over the req.body using forEach and set the each data to be added in to the collection using the set method
We commit the data and save the data to the collection using the commit method and on success ,send a success response.
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:
Sam Stern's answer is the correct way to do it, although if you are using AngularFire, .doc() cannot be used withouth a parameter to generate a new docId (see https://github.com/angular/angularfire/issues/1974).
The AngularFire way of doing this would be:
// Create a ref with auto-generated ID
const id = this.db.createId();
const newCityRef= this.db.collection("cities").doc(id);
// ...
// Add it in the batch
batch.set(newCityRef, { name: 'New York City' });
This worked for me and it is mentioned in the docs for PHP
$batch = $db->batch();
# Set the data for NYC
$nycRef = $db->collection('samples/php/cities')->document('NYC');
$batch->set($nycRef, [
'name' => 'New York City'
]);
# Update the population for SF
$sfRef = $db->collection('samples/php/cities')->document('SF');
$batch->update($sfRef, [
['path' => 'population', 'value' => 1000000]
]);
# Delete LA
$laRef = $db->collection('samples/php/cities')->document('LA');
$batch->delete($laRef);
# Commit the batch
$batch->commit();
To create a document with auto-generated ID with firestore batch, you cannot use the addDoc(). You have to use batch.set() with a reference to the document to be created as below
// Create a transaction to update both the product stock value and add the new stock data
const batch = writeBatch(getFirestore());
const prodRef = doc(getFirestore(), `products/${productId}`);
const stockRef = doc(collection(getFirestore(),`stocks`);
// newDocId = stockRef.id;
batch.set(stockRef, stock, {merge: true}); //create new document with autoId
batch.update(prodRef, {available : increment(quantity), stock: increment(quantity)});
batch.commit()