Question #7207   Submitted by Answiki on 11/05/2023 at 10:35:06 AM UTC

With Firestore, how to create a batch write with autogenerated IDs and get the ID?

Answer   Submitted by Answiki on 11/05/2023 at 10:48:58 AM UTC

With Firebase / Firestore, the following code can be used to create a new document with an auto-generated ID in a batch write. As soon as the document is created with newDocRef = doc(collection(db, ...)), the new generated ID is available at newDocRef.id:


// Get a new write batch
const batch = writeBatch(db);

// Create a new document with an auto-generated ID in the collection collectionName
const newDocRef = doc(collection(db, "collectionName"));

// Get the new document ID
const id =  newDocRef.id;

// Set the data to the new document
batch.set(newDocRef, { key1: "value1", key2: "value2");

// Commit 
batch.commit()

4 events in history
Question by Answiki 11/05/2023 at 10:49:34 AM
How to get the autogenerated ID of document created in a batch write with Firestore?
Answer by Answiki on 11/05/2023 at 10:48:58 AM

With Firebase / Firestore, the following code can be used to create a new document with an auto-generated ID in a batch write. As soon as the document is created with newDocRef = doc(collection(db, ...)), the new generated ID is available at newDocRef.id:


// Get a new write batch
const batch = writeBatch(db);

// Create a new document with an auto-generated ID in the collection collectionName
const newDocRef = doc(collection(db, "collectionName"));

// Get the new document ID
const id =  newDocRef.id;

// Set the data to the new document
batch.set(newDocRef, { key1: "value1", key2: "value2");

// Commit 
batch.commit()

Answer by Answiki on 11/05/2023 at 10:43:29 AM

With Firebase / Firestore, the following code can be used to create a new document with an auto-generated ID in a batch write and retrieve the new ID once the batch is commited:


// Get a new write batch
const batch = writeBatch(db);

// Create a new document with an auto-generated ID in the collection collectionName
const newDocRef = doc(collection(db, "collectionName"));

// Set the data to the new document
batch.set(newDocRef, { key1: "value1", key2: "value2");

// Commit 
batch.commit()
  .then(() => {
    // Get the auto-generated ID once the commit is successful
    console.log(newDocRef.id);
  })
  .catch((error) => { console.error(error); })

Question by Answiki 11/05/2023 at 10:35:06 AM
With Firestore, how to create a batch write with autogenerated IDs and get the ID?
# ID Query URL Count

Icons proudly provided by Friconix.