Ask Your Question
2

How can a batch write statement be executed within a forEach() loop in Firestore?

asked 2021-07-25 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-01-03 18:00:00 +0000

pufferfish gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-07-25 11:00:00 +0000

Seen: 12 times

Last updated: Jan 03 '23