Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To execute a batch write statement within a forEach() loop in Firestore, you can follow these steps:

  1. Create an instance of the Firestore client using the Firebase SDK.
  2. Create an empty batch object using the batch() method of the Firestore client.
  3. Loop through the array of documents using the forEach() method.
  4. For each document, call the set() method on the batch object to set the data.
  5. After setting all the data, call the commit() method on the batch object to commit the write operation.

Here's an example code snippet that demonstrates the above steps:

const admin = require('firebase-admin');
const serviceAccount = require('./path/to/serviceAccountKey.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://your-project-id.firebaseio.com',
});

const firestore = admin.firestore();

const docs = [
  { id: 'doc1', data: { name: 'John Doe', age: 25 } },
  { id: 'doc2', data: { name: 'Jane Doe', age: 30 } },
  { id: 'doc3', data: { name: 'Bob Smith', age: 35 } },
];

const batch = firestore.batch();

docs.forEach((doc) => {
  const ref = firestore.collection('users').doc(doc.id);
  batch.set(ref, doc.data);
});

batch.commit()
  .then(() => console.log('Batch write successful'))
  .catch((error) => console.error('Error writing documents: ', error));

In the above example, we first initialize the Firestore client using the credentials from a service account file. Next, we define an array of documents to write to the database.

We create an empty batch object using the batch() method of the Firestore client. Then, we loop through the array of documents using the forEach() method, and for each document, we call the set() method on the batch object to set the data.

Finally, we call the commit() method on the batch object to commit the write operation. If the write operation is successful, we log a message to the console. Otherwise, we log the error.