To execute a batch write statement within a forEach() loop in Firestore, you can follow these steps:
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.
Asked: 2021-07-25 11:00:00 +0000
Seen: 12 times
Last updated: Jan 03 '23