With Firestore, how to create a batch write with autogenerated IDs and get the ID?
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()
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()
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); })
# | ID | Query | URL | Count |
---|